-3
我正试图在ruby上做一个简单的代数计算器应用程序,但我在编码时遇到了一个问题。我使用的.split方法将方程分成“部分”(用正号和负号分隔),但方程eq用+符号分开,但它不带有 - 符号。.split()方法无法在ruby上工作
eq = gets.chomp
a = []
a = eq.split("+")
a.each do |n|
case n
when n.include?("-")
a << n.split("-")
end
end
print a[0], ";", a[1]
我使用的情况,因为如果我没有,它返回一个NoMethod错误。我已经制作了一个普通的计算器,所以我认为这会成为一个很好的下一个项目。我也想知道你是否有任何想法缩短我的代码;也许通过创建一个方法。以下是我常用的计算器代码,我也想知道如何缩短。
loop do
print
equation = gets.chomp
if equation.include?"^"
exponent_e = equation.split("^")
result_e = exponent_e[0].to_f ** exponent_e[1].to_f
print " = #{result_e} "
puts
elsif equation.include?"%"
percent_e = equation.split("%")
number = percent_e[0].to_f/100
result_p = number * percent_e[1].to_f
print " = #{result_p} "
puts
elsif equation.include?"/"
res_d = equation.split("/")
result_d = res_d[0].to_f/res_d[1].to_f
print " = #{result_d} "
puts
elsif equation.include?"*"
res_m = equation.split("*")
result_m = res_m[0].to_f * res_m[1].to_f
print " = #{result_m} "
puts
elsif equation.include?"+"
res_a = equation.split("+")
result_a = res_a[0].to_f + res_a[1].to_f
print " = #{result_a} "
puts
elsif equation.include?"-"
res_s = equation.split("-")
result_s = res_s[0].to_f - res_s[1].to_f
print " = #{result_s} "
puts
else
puts "Input valid equation"
end
end
请让我们知道您的预期行为和实际行为。很难解决“它没有工作”。 – msergeant