我试图在Ruby中编写一个程序来评估一个人可以交换多少瓶装以获得额外的苏打水,以及他们可以继续使用多长时间,直到他们无法进行交易 我很难想象这是如何运作的。但到目前为止,这就是我所拥有的。
规则:
User currently has 10 bottlecaps
They can trade in 3 bottlecaps to get a soda
User trades in 9/10 bottlecaps to get 3 extra sodas
Now they have 4 bottlecaps (1 left over and the 3 that were traded in)
They can trade in 3 more bottlecaps to get one extra soda
Now they have 1 bottlecap, and cannot trade in anymore
这是我到目前为止所拥有的
bottlecaps = 10
for_trade = 3
traded_sodas = bottlecaps / for_trade
num_bottlecaps_traded = for_trade * traded_sodas
bottlecaps = bottlecaps - num_bottlecaps_traded
但是我需要弄清楚如何让它循环直到用户再也无法交易瓶盖。任何人都可以提供任何指示吗?
答案 0 :(得分:4)
Ruby可以像这样永远循环
loop do
# code in here runs over and over again
end
要停止循环,您可以使用break
关键字并检查指示循环应该结束的某些条件,在您的情况下
loop do
break if bottlecaps < for_trade
# trade bottlecaps...
end
编写此类循环的更简洁方法是在每次重复之前检查条件,使用until
until bottlecaps < for_trade
# trade bottlecaps
end
或者如果你想更积极地思考
while bottlecaps >= for_trade
# trade bottlecaps
end