我编写了一个简单的计算例子,但它不起作用
a = IO.gets"a = "
a = String.to_integer(a)
b = IO.gets"b = "
b = String.to_integer(b)
v = a + b
IO.puts "Sum: #{v}"
如何更正此代码?
答案 0 :(得分:3)
IO.gets
也不会修剪使String.to_integer
失败的尾随换行符。您可以使用String.trim_trailing/1
删除它:
a = IO.gets("a = ") |> String.trim_trailing
a = String.to_integer(a)
b = IO.gets("b = ") |> String.trim_trailing
b = String.to_integer(b)
v = a + b
IO.puts "Sum: #{v}"
$ elixir a.exs
a = 123
b = 456
Sum: 579