0

我是 Erlang 初学者,正在尝试制作一个简单的命令行应用程序,用户可以在其中输入地板的宽度和高度、每平方英尺地板的成本,然后返回价格。本质上,我只是接受三个整数值并返回产品。

23> c(costcalc).
{ok,costcalc}
24> costcalc:start().
Calculate the cost of flooring based on width, height, and cost per square foot.

Width in feet: 5
Height in feet: 5
Cost in dollars per square foot: $4
** exception error: an error occurred when evaluating an arithmetic expression in function  costcalc:start/0 (costcalc.erl, line 23)

这是我正在使用的代码:

start() ->
  io:format("Calculate the cost of flooring based on width, height, and cost per square foot.\n"),
  W = string:to_integer(io:get_line("Width in feet: ")),
  H = string:to_integer(io:get_line("Height in feet: ")),
  C = string:to_integer(io:get_line("Cost in dollars per square foot: $")),
  Cost = W * H * C,
  io:fwrite(Cost).

第 23 行Cost = W * H * C,应该是 100。当我5 * 5 * 4.直接在 shell 中运行时,它可以毫无问题地计算。我还应该注意,无论我是否使用我想我可以不用的 string:to_integer() 都会发生这种情况。

我错过了什么?

4

2 回答 2

2

正如@Khashayar 所提到的,您的代码中的问题是string:to_integer/1返回一对(具有两个元素的元组)并且整数是第一个元素。

但是,您不应该使用此功能。Erlang 中的字符串只是一个整数列表,您打算使用的是list_to_integer/1. 这是将字符串转换为整数的常用方法。

如果您使用list_to_integer/1,您将避免@Khashayar 代码中第二对元素与任何内容匹配的错误。实际上,您可以输入以下内容:

Calculate the cost of flooring based on width, height, and cost per square foot. 
Width in feet: 1.9
Height in feet: 1.9
Cost in dollars per square foot: $ 4.9
4

虽然1.9*1.9*4.9实际上等于17.689

不幸的是,没有list_to_number/1函数可以返回整数或浮点数。处理此问题的最常见方法是执行 try/catchlist_to_float/1并回退到list_to_integer/1. 或者,您可以使用io_lib:fread/2or string:to_float/1which 不会引发异常(仍然,如上所述,使用string:to_float/1被认为是一种不好的做法)。

于 2013-08-07T13:15:38.593 回答
1

您遇到的问题是字符串:to_integer,它返回 2 个值!你应该像这样使用它们。

start() ->
    io:format("Calculate the cost of flooring based on width, height, and cost per square foot.\n"),
    {W,_} = string:to_integer(io:get_line("Width in feet: ")),
    {H,_} = string:to_integer(io:get_line("Height in feet: ")),
    {C,_} = string:to_integer(io:get_line("Cost in dollars per square foot: $ ")),
    Cost = (W * H) * C,
    io:fwrite("~p~n",[Cost]).

顺便说一下,第二个值是字符串的其余部分,

to_integer(String) -> {Int, Rest} | {错误,原因}

祝你好运

于 2013-08-07T11:33:32.223 回答