erlang:计算算术表达式时出现异常错误
erlang: exception error when evaluating an arithmetic expression
-module(test2).
-export([main/1]).
calc(Cnt, Total) when Cnt > 0 ->
calc(Cnt - 1, (Total + 2 * 34 + 1) / 2 * 39);
calc(0, Total)->
io:format("~p ~n", [Total]),
ok.
main([A])->
Cnt = list_to_integer(A),
calc(Cnt, 1).
执行上面的代码很奇怪:
$ escript test2.beam 900000000
escript: exception error: an error occurred when evaluating an arithmetic expression
in function test2:calc/2 (test2.erl, line 4)
in call from escript:run/2 (escript.erl, line 752)
in call from escript:start/1 (escript.erl, line 276)
in call from init:start_it/1
in call from init:start_em/1
如果我删除 * 39
,那么一切正常。
有什么问题?
浮点数溢出。浮点除法运算符 /
将您的 Total
变量转换为双精度浮点数。迭代一定次数后,与39相乘的结果超出了该类型所能容纳的最大值
-module(test2).
-export([main/1]).
calc(Cnt, Total) when Cnt > 0 ->
calc(Cnt - 1, (Total + 2 * 34 + 1) / 2 * 39);
calc(0, Total)->
io:format("~p ~n", [Total]),
ok.
main([A])->
Cnt = list_to_integer(A),
calc(Cnt, 1).
执行上面的代码很奇怪:
$ escript test2.beam 900000000
escript: exception error: an error occurred when evaluating an arithmetic expression
in function test2:calc/2 (test2.erl, line 4)
in call from escript:run/2 (escript.erl, line 752)
in call from escript:start/1 (escript.erl, line 276)
in call from init:start_it/1
in call from init:start_em/1
如果我删除 * 39
,那么一切正常。
有什么问题?
浮点数溢出。浮点除法运算符 /
将您的 Total
变量转换为双精度浮点数。迭代一定次数后,与39相乘的结果超出了该类型所能容纳的最大值