Ruby - 如何让这个程序移动到下一个等式?
我只是学习编程,所以这是一个新手question.I'm试图启动非常简单,但不能让我的头解决这个问题。Ruby - 如何让这个程序移动到下一个等式?
我正在写一个程序,它要求用户的答案,一个给定的公式。像8次9
程序应该问什么是答案的方程式,取号(总和)作为输入从用户回答公式是什么。如果用户是正确的,那就是说“正确!”并为他们的分数添加一个分数。如果用户不正确,则表示“不正确,答案是:x”,并生成另一个等式而不在其分数中添加一个分数。
搭配方案,因为它是,这是,如果用户不正确,会发生什么:Incorrect answer
这是如果用户是正确的会发生什么:Correct
如何使一个循环,使该程序移动到下一个等式?我尝试过尝试不同的方法,但我无法设法得到它。
这里是我的代码...
# Assigns random number to n1
n1 = rand(11)
# Assigns random number to n2
n2 = rand(11)
# Puts together the equation
q = String(n1) + " times " + String(n2)
# Gets the answer ready
a = n1 * n2
# Self explanatory
gamesPlayed = 0
score = 0
# Asks for sum answer
puts("What is " + q + "?")
# Takes users guess
g = gets()
#
# This is where I'm stuck
#
# This loop is supposed to make the game move onto the next equation
while Integer(g) == a
puts("Correct!")
# Supposed to add to the score
score += 1
end
puts("Incorrect, answer is: " + String(a))
gamesPlayed += 1
#^Supposed to move to next equation
# Not sure if necessary - Supposed to make program stop after third question
if gamesPlayed == 2
gamesPlayed += 1
else
end
# Self explanatory
puts("Game over, you scored: " + String(score))
附:任何帮助解决这个问题和对代码的一些建设性的批评是非常感谢。 UPDATE
我将代码改为建议的内容,并且大部分工作。尽管仍然存在问题,但花了很长时间才弄清楚。
gamesPlayed = 0
score = 0
while gamesPlayed != 2
n1 = rand(11)
n2 = rand(11)
a = n1 * n2
q = String(n1) + " times " + String(n2)
puts("What is " + q + "?")
g = gets()
if g == a # where the problem was
puts("Correct!")
score += 1
gamesPlayed += 1
else
puts("Incorrect, answer is: " + String(a))
gamesPlayed += 1
end
end
puts("Game over, you scored: " + String(score))
我改变了,如果条件从if g == a
到if Integer(g) == a
,现在的作品!
到目前为止,你只生成一个公式,如RAND()只调用一次。你想把它放在while循环中。作为小费,如果你被卡住,创建你正在尝试完成的步骤是一个计划,然后比较,为你的代码做什么。
至于你的代码:
gamesPlayed = 0
score = 0
while gamesPlayed != 2
n1 = rand(11)
n2 = rand(11)
a = n1*n2
q = String(n1) + " times " + String(n2)
puts("What is " + q + "?")
g = gets()
if g == a
puts("Correct!")
score += 1
gamesPlayed += 1
else
puts("Incorrect, answer is: " + String(a))
gamesPlayed += 1
end
end
puts("Game over, you scored: " + String(score))
希望这有助于!
感谢您的回复,我明白您的意思。我尝试在while循环中嵌套if条件,但是我发现我做的不正确。然而,你的代码中的最后一行。 'puts(“游戏结束,你得分:”+ String(得分))'当我运行它时,出现语法错误:game.rb:19:语法错误,意外的输入结束,期待keyword_end puts(“游戏结束,你得分:“+ String(分数))这里有什么问题? – user3587172
对不起。我忘了为while循环添加最后的结束语句,这就是错误标记的原因。尝试修改后的代码。它应该这次工作。 – Cbeb24404
下一步做什么方程?只有一个等式,没有下一个。 –