我正在尝试用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
但我需要弄清楚如何让这个循环,直到用户不能再交易瓶盖有人能指点一下吗?
最佳答案
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