我正在制作一个可以计算加,减,乘和除的计算器:
puts "This is Calculator"
print "please enter the number 1"
a = gets.to_i
puts "please enter number 2"
b = gets.to_i
puts "please choose your operation"
c = gets
if c = add
puts a+b
elsif c = sub
puts a-b
elsif c = mul
puts a*b
elsif c = div
puts a/b
end
答案 0 :(得分:2)
一些修复:
=
用于分配,==
用于比较gets
甚至会输入您输入的内容,因此在将其与add,sub,mul和div进行比较之前,我们先将其剔除以这种方式似乎起作用:
puts "This is Calculator"
print "please enter the number 1"
a = gets.to_i
puts "please enter number 2"
b = gets.to_i
puts "please choose your operation"
c = gets.chomp
if c == "add"
puts a+b
elsif c == "sub"
puts a-b
elsif c == "mul"
puts a*b
elsif c == "div"
puts a/b
end
显然没有错误处理
答案 1 :(得分:0)
puts "This is Calculator"
print "please enter the number 1 :- "
a = gets.to_i
puts "please enter number 2 :- "
b = gets.to_i
puts "please choose your operation (add / sub / mul / div) :- "
c = gets
if c == "add\n"
puts a+b
elsif c == "sub\n"
puts a-b
elsif c == "mul\n"
puts a*b
elsif c == "div\n"
puts a/b
end
这是您的解决方案,但您应该对其进行更多格式化, 如果您想知道代码为何起作用,请发表评论。