我正在制作计算器,但无法正常工作

时间:2018-11-22 12:15:40

标签: ruby

我正在制作一个可以计算加,减,乘和除的计算器:

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

2 个答案:

答案 0 :(得分:2)

一些修复:

  • =用于分配,==用于比较
  • 字符串需要使用beetwen引号
  • 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

这是您的解决方案,但您应该对其进行更多格式化, 如果您想知道代码为何起作用,请发表评论。