使用 float_of_int 进行类型转换

Type conversion with float_of_int

我开始使用 ocaml 并尝试过:

float_of_int 8/2;;

我原以为它是 returns 4.0,因为 8/2 是 4,但我收到一条错误消息:

Error: This expression has type float but an expression was expected of type
int 

我在这里错过了什么?

你的表达式是这样解析的:

(float_of_int 8) / 2

所以你要求使用 / 来划分浮点数,这适用于整数。

函数应用(在OCaml中通过并排放置两个表达式来表示)具有非常高的优先级,高于所有二元中缀运算符。所以你需要使用括号。

如果你这样写就可以了:

float_of_int (8/2)

阅读 Jeffrey 的回答后,我找到了另一种使用表达式的方法,虽然语句稍长:

float_of_int 8/. float_of_int 2;;