在Ruby上制作计算器时出错?

时间:2015-11-04 23:03:08

标签: ruby calculator

尝试使用TextWrangler'#在Ruby中制作计算器时!功能(在终端编译)我遇到了一个错误。当我添加2 + 2时,它返回的答案是2.0。我尝试了其他功能,例如计算某个数字的特定百分比,无论我尝试做什么,答案总是0.0。我检查了语法,使用了#!功能,没有错误。我知道我犯了不必要的错误,但对我来说这样更方便。

loop do
print 
equation = gets.chomp

if equation.include?"^"
    exponent_e = equation.split("^")
    result_e = equation[0].to_f ** equation[1].to_f
    puts "#{equation} = #{result_e}"
elsif equation.include?"%"
    percent_e = equation.split("%")
    number = equation[0].to_f / 100
    result_p = number * equation[1].to_f
    puts "#{equation} = #{result_p}"
elsif equation.include?"/"
    equation.split("/")
    result_d = equation[0].to_f / equation[1].to_f
    puts "#{equation} = #{result_d}"
elsif equation.include?"*"
    equation.split("*")
    result_m = equation[0].to_f * equation[1].to_f
    puts "#{equation} = #{result_m}"
elsif equation.include?"+"
    equation.split("+")
    result_a = equation[0].to_f + equation[1].to_f
    puts "#{equation} = #{result_a}"
elsif equation.include?"-"
    equation.split("-")
    result_s = eqaution[0].to_f - equation[1].to_f
    puts "#{equation} = #{result_s}"
end
end

1 个答案:

答案 0 :(得分:2)

您不是将分割存储在变量中。你需要做这样的事情:

elsif equation.include?"+"
    res = equation.split("+")
    result_a = res[0].to_f + res[1].to_f