我的代码在Ruby运行,但没有输出帮助请

brtdzjyr  于 2023-03-17  发布在  Ruby
关注(0)|答案(1)|浏览(102)

我制作了一个简单的calactor代码,它可以运行,但不会返回最终用户所需的总和
我的代码是:

def calculator(num1,num2)
  puts"Enter you first number"
  num1 = gets.chomp

  puts " Enter operator"
  opp = gets.chomp.to_f

  puts"enter your second number \u{2753}"

  num2 = gets.chomp.to_f
  
  if opp == "+"
    puts"num1+num2"
  
  elsif opp =="-"
    puts "num1- num2"
  
  elsif opp == "/"
    puts"num1/num2"
  
  elsif opp == "*"
    puts"num1*num2"
  
  elsif opp == "%"
    puts"num1%num2"
  
  else
    puts"Wrong operator"
    
  puts"Your Result is #{calculator(num1,num2)}"
end
b09cbbtk

b09cbbtk1#

这段代码还有许多其他问题,但根本无法输出的主要问题是if/else条件缺少结尾。

def calculator(num1,num2)
  puts"Enter you first number"
  num1 = gets.chomp

  puts " Enter operator"
  opp = gets.chomp.to_f

  puts"enter your second number \u{2753}"

  num2 = gets.chomp.to_f
  
  if opp == "+"
    puts"num1+num2"
  
  elsif opp =="-"
    puts "num1- num2"
  
  elsif opp == "/"
    puts"num1/num2"
  
  elsif opp == "*"
    puts"num1*num2"
  
  elsif opp == "%"
    puts"num1%num2"
  
  else
    puts"Wrong operator"
  end

  puts"Your Result is #{calculator(num1,num2)}"
end

另一个主要的问题是你在calculator方法中递归调用calculator方法,导致递归。我不确定你期望的输出是什么,但是你可以这样做:

def calculator(num1, num2)
  puts "Enter your first number"
  num1 = gets.chomp.to_f

  puts "Enter operator"
  opp = gets.chomp

  puts "Enter your second number"
  num2 = gets.chomp.to_f
  
  case opp
  when "+"
    result = num1 + num2
    puts "Result: #{result}"
  when "-"
    result = num1 - num2
    puts "Result: #{result}"
  when "/"
    result = num1 / num2
    puts "Result: #{result}"
  when "*"
    result = num1 * num2
    puts "Result: #{result}"
  when "%"
    result = num1 % num2
    puts "Result: #{result}"
  else
    puts "Wrong operator"
  end
end

calculator(0, 0)

相关问题