【发布时间】:2023-02-25 21:59:57
【问题描述】:
我制作了一个阶乘函数,当然可以让我计算阶乘,正如我们所知,一个阶乘永远不能 < 0.我的代码有时给了我负数......这是:
exception FactorialError of string;;
let rec factorial (n: int) : int = (
if n < 0 then raise (FactorialError "The number has to be upper or equal then 0");
if n == 0 then 1 else n * factorial(n-1);
);;
let value = ref (1);;
for i = 0 to 100 do
(
value := factorial i;
if !value = 0 then raise (FactorialError ("Factorial is no more possible after i = " ^
string_of_int i)) else print_string ("i: " ^ string_of_int i);
print_string "\nValue: ";
print_int !value;
print_string "\n";
)
done;;
以下是其中一些的结果:
i: 0
Value: 1
i: 1
Value: 1
...
i: 20
Value : 2432902008176640000
i: 21
Value : -4249290049419214848 // <- Here is the problem
...这是问题,但不仅是 21 值,还有许多其他...
【问题讨论】:
-
好像整数溢出:当整数超过它的 MaxValue 你得到消极的结果