Ruby-如何让这个程序进入下一个等式?

Ruby-如何让这个程序进入下一个等式?,ruby,Ruby,我只是在学习编程,所以这是一个新手问题。我试图从一个非常简单的问题开始,但我无法解决这个问题 我正在编写一个程序,要求用户对给定的方程式给出答案。比如8乘9 程序应该询问一个等式的答案是什么,从用户那里获取一个数字和作为输入来回答这个等式是什么。如果用户是正确的,就意味着说正确!给他们的分数加一分。如果用户是不正确的,这意味着说不正确,答案是:x,并生成另一个方程,而不给他们的分数加一分 按照程序的原样,如果用户不正确,会发生以下情况: 如果用户是正确的,就会发生这种情况: 我如何做一个循环,使

我只是在学习编程,所以这是一个新手问题。我试图从一个非常简单的问题开始,但我无法解决这个问题

我正在编写一个程序,要求用户对给定的方程式给出答案。比如8乘9

程序应该询问一个等式的答案是什么,从用户那里获取一个数字和作为输入来回答这个等式是什么。如果用户是正确的,就意味着说正确!给他们的分数加一分。如果用户是不正确的,这意味着说不正确,答案是:x,并生成另一个方程,而不给他们的分数加一分

按照程序的原样,如果用户不正确,会发生以下情况:

如果用户是正确的,就会发生这种情况:

我如何做一个循环,使程序移动到下一个等式?我试过用不同的方法来做实验,但我没法做到

这是我的密码

# 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))
请注意,我们非常感谢您在解决此问题上提供的任何帮助以及对准则提出的一些建设性批评。 更新

我将代码更改为建议的代码,大部分代码都有效。虽然仍然有一个问题,但我花了很长时间才解决

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条件从if g==a改为if Integerg==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))

希望这有帮助

下一个等式是什么?只有一个等式,没有下一个。谢谢你的回答,我明白你的意思。我尝试将if条件嵌套在while循环中,但我发现我做得不对。但是,代码中的最后一行。putsGame结束,你得分:+Stringscore我运行它时出现语法错误:游戏。rb:19:语法错误,输入意外结束,期望关键字\u end putsGame结束,你得分:+Stringscore这里有什么问题?抱歉。我忘了为while循环添加最后的end语句,这就是错误标记的内容。试试修改后的代码。这次应该行得通。