【问题标题】:erlang: exception error when evaluating an arithmetic expressionerlang:评估算术表达式时出现异常错误
【发布时间】:2015-07-03 09:58:55
【问题描述】:
-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,那么一切正常。

有什么问题?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    浮点溢出。浮点除法运算符/ 将您的Total 变量转换为双精度浮点数。经过一定次数的迭代,乘以39的结果超过了该类型所能容纳的最大值。

    【讨论】:

    • 那么整数是任意大小,永远不会溢出,而浮点数是固定大小,会溢出?
    猜你喜欢
    • 2019-07-25
    • 2019-04-08
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多