Ruby - 如何让这个程序转移到下一个等式?

时间:2016-11-20 09:04:25

标签: 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))

P.S。任何有关解决此问题的帮助以及对代码的一些建设性批评都非常感谢。 的更新

我将代码更改为建议的内容,并且它在大多数情况下都有效。虽然还有问题,但我花了很长时间才搞清楚。

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 Integer(g) == a,现在可以使用了!

1 个答案:

答案 0 :(得分:1)

到目前为止,您只生成一个等式,因为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))

希望这有帮助!