这里是 OCaml 新手。
我试图弄清楚当从 float 转换为 int 时如何处理 OCaml 中的整数溢出。
我希望使用 try ... with ...
或将其与 nan
进行比较(因为实际上 has to return nan when float is too large ?),但看起来确实如此不抛出任何错误。
更令人惊讶的是,对于非常大的 float int_of_float 只返回 0
。
utop # 0 = int_of_float 9999999999999999999.0;;
- : bool = true
utop # int_of_float 9999999999999999999.0;;
- : int = 0
如何正确处理 float 到 int 的转换? (更常见的是 int 溢出?)
最佳答案
确实,OCaml's manual表示 float_of_int
的“如果参数为 nan 或超出可表示的整数范围,则结果未指定。”
一种可能性是预先检查您的 float 是否适合,并返回一个选项或引发异常,例如
let safe_int_of_float f =
if classify_float f = FP_nan then None
else if f >= float_of_int max_int then None
else if f <= float_of_int min_int then None
else Some (int_of_float f)
关于error-handling - 使用 int_of_float 从浮点转换时如何处理 OCaml 中的整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871692/