所以我在查找3个数字之间的中间数字时遇到问题。我写了代码,但收到"Exception: Failure "int_of_string"
消息。你知道为什么吗?
let minimum a b c = min a (min b c)
let maximum a b c = max a (max b c)
let middle a b c =if a > (minimum a b c) && a < (maximum a b c) then Printf.printf "The middle is %d" a;
if b > (minimum a b c) && b < (maximum a b c) then Printf.printf "The middle is %d" b;
if c > (minimum a b c) && c < (maximum a b c) then Printf.printf "The middle is %d" c
let () = print_string "Enter x: "
let x = read_int ()
let () = print_string "Enter y: "
let y = read_int ()
let () = print_string "Enter z: "
let z = read_int ()
let mid = middle x y z;;
当我运行它时,我得到了:
let minimum a b c = min a (min b c)
let maximum a b c = max a (max b c)
let mediana a b c = if a > (minimum a b c) && a < (maximum a b c) then Printf.printf "The middle is %d" a;
if b > (minimum a b c) && b < (maximum a b c) then Printf.printf "The middle is %d" b;
if c > (minimum a b c) && c < (maximum a b c) then Printf.printf "The middle is %d" c
let () = print_string "Enter x: "
let x = read_int ()
let () = print_string "Enter y: "
let y = read_int ()
let () = print_string "Enter z: "
let z = read_int ()
let mid = middle x y z;;
Enter x:
Exception: Failure "int_of_string".
#
答案 0 :(得分:2)
如果我使用ocaml
或utop
命令从Linux shell启动全新的解释器,然后将您的第一个代码复制/粘贴到其中,那么输入该数字就没有问题。
但是,如果代码中;;
后面有空白行,则ocaml
解释器会将其视为x
的输入,实际上直接抱怨空行不能转换为数字,导致出现您描述的症状。因此,我建议您在提供解释器时要小心,不要复制多余的字符(尤其是换行符),或切换到utop
,这不会表现出这种现象,并且顶层更好,带有命令历史记录和自动补全功能。