我在Ruby中的代码运行但不产生输出[关闭]

xytpbqjk  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(111)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
17天前关闭。
Improve this question
我已经做了一个简单的计算器代码,运行,但它不会返回的总和最终用户正在寻找。
我的代码是:

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
brccelvz

brccelvz1#

这段代码还有许多其他问题,但根本无法输出的主要问题是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)

相关问题