ocaml - 如何将用户输入值添加到 Ocaml 中的数组
问题描述
我在 OCaml 工作,必须解决以下问题
7.1 Problem 1 – Number of values less than average
Input: 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 values
Sample input:
Enter the count and the corresponding integer values:
7 10 60 3 55 15 45 40
Corresponding output:
The list:
10 60 3 55 15 45 40
The average:
32.57
Number of values less than average:
3
这个想法是使用用户输入,获取要平均的数字长度,获取要平均的数字,平均它们,然后告诉列表中哪些数字小于平均值。我的问题在于尝试将用户给出的值添加到数组中。我能够创建数组,但不知道使用什么代码来添加值。
我目前的代码...
(* Prompts the user to enter the number of values they want to average
then 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 then
adds 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;;
有问题的代码是...
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;;
我已经尝试了当前注释掉的内容,a.(i) <- values
但没有添加,它给了我一个错误
Fatal error: exception Scanf.Scan_failure("scanf: bad input at char number 1: character ' ' is not a decimal digit")
解决方案
如果您包含注释掉的代码,您将拥有:
let values = Scanf.scanf "%d" (fun n -> n)
a.(i) <- i
这在语法上无效,因为它有 a let
with no in
。您对问题的描述不够具体,无法判断这是否是您的问题。如果是这样,您需要in
在第一行的右括号后添加。
如果这不是您的问题,您可能会注意到这里的第二行代码没有使用values
,尽管这几乎是我期望它做的。目前的代码从标准输入读取一个值,然后忽略它读取的值。
如果这些都不是您的问题,您需要更仔细地描述您的问题。如果你只说“它没有用”,那就很难提供帮助。
推荐阅读
- javascript - 如何在不使用 document.write() 的情况下在 Javascript 中开始新行?
- sql - 使用“with”函数和中位数有困难
- python - 索引ndarray时应该如何使用arange函数?
- azure - Azure APIM 控制在开发人员门户中显示哪些 API
- ocaml - OCaml-图像 (.png) 到颜色数组
- twitter-bootstrap-3 - 如何使用较新版本的 Less 运行 Bootstrap 3.0.2?
- unit-testing - 在 Nestjs 的单元测试中模拟服务
- asp.net-mvc - 在 ASP.NET MVC 中不使用 HTML 表单将数据发布到控制器
- javascript - 在浏览器窗口中居中,适用于 safari 但不适用于 firefox 或 chrome
- spring-batch - 如何使用 DbUnit 设置 Spring Batch?