我正在开发一个程序,为用户提供两个随机数,范围从0到10,供用户进行分割,乘法,加法或减法。
在每个问题之后,用户都有机会通过键入no
来停止该程序。
我正在使用while
循环,但是当用户输入no
时,我无法终止循环。如何让程序正确响应用户输入?
def math_num
nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/", "*"].sample]
problem = "What is #{num_1} #{operator} #{num_2}?"
puts problem
$input = gets.to_i
$answer = num_1.send(operator, num_2)
puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"
def try_again
puts "Would you like to do another question?"
another = gets.chomp.to_s
while another != "no"
math_num
end
end
try_again
end
math_num
答案 0 :(得分:2)
好吧,你这样做的方式是你得到一个无限循环,因为another
变量的值没有在while
循环中更新。
请改为尝试:
def math_num
while true
nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/","*"].sample]
problem = "What is #{num_1} #{operator} #{num_2}?"
puts problem
$input = gets.to_i
$answer = num_1.send(operator, num_2)
puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"
puts "Would you like to do another question?"
another = gets.chomp.to_s
if another == "no"
break
end
end
end
math_num