Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 528

How to add user input values to an array in Ocaml

$
0
0

I am working in OCaml and have to do the following problem

7.1 Problem 1 – Number of values less than averageInput: An integer, listlen, followed by listlen number of integer values.Output: The list of values, number of items on the list, and the number of input values that are less than the average of all the valuesSample input:Enter the count and the corresponding integer values:7 10 60 3 55 15 45 40Corresponding output:The list:10 60 3 55 15 45 40The average:32.57Number of values less than average:3

The idea is to use user input, get a length of numbers to be averaged, get the numbers to be averaged, average them and then tell which numbers from the list are less than the average. My issue comes in trying to add the values given from the user into the array. I was able to create the array but can't figure out what code to use to add the values.

The code I have currently...

(* Prompts the user to enter the number of values they want to averagethen gets that number and prints it *)print_string "Enter The Number of Values You Want To Average:\n";;let n_values = Scanf.scanf "%d" (fun n -> n);;Printf.printf "%d\n" n_values;;(* Prompts the user to enter the numbers they want averaged thenadds those values to an array and prints the numbers *)print_string "Enter The Values To Be Averaged:\n";;let a = Array.make n_values 0;;for i = 0 to Array.length a - 1 do    (*let values = Scanf.scanf "%d" (fun n -> n)*)    a.(i) <- i  done;;for i = 0 to Array.length a - 1 do    Printf.printf "%i" a.(i);done;;(* Adds each of the values of the array together, stores it in sum and then divides by the n_values initialized above and stores in average, then prints this value *)print_string "\nThe Average:\n";;let sum = Array.fold_left (+) 0 a;;let average = sum / n_values;;Printf.printf "%d\n" average;;(* Checks which numbers in the array are less than the computed average and increments a counter if it is less*)print_string "The Number of Values Less Than The Average:\n";;let counter = ref 0;;for i = 0 to Array.length a - 1 do   if a.(i) < average then incr counter;done;;Printf.printf "%d\n" !counter;;

The code in question is...

let a = Array.make n_values 0;;for i = 0 to Array.length a - 1 do    (*let values = Scanf.scanf "%d" (fun n -> n)*)    a.(i) <- i  done;;for i = 0 to Array.length a - 1 do    Printf.printf "%i" a.(i);done;;

I have tried what is currently commented out w/ adding a.(i) <- values but that did not work and it gave me an error of Fatal error: exception Scanf.Scan_failure("scanf: bad input at char number 1: character '' is not a decimal digit")


Viewing all articles
Browse latest Browse all 528

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>