【问题标题】:Ruby: Writing a Looping Program that Runs until resources are exhausted?Ruby:编写一个一直运行到资源耗尽的循环程序?
【发布时间】:2018-06-15 17:55:52
【问题描述】:

我正在尝试用 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 loops for-loop while-loop


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 2016-06-29
      相关资源
      最近更新 更多