在Ruby中返回值from until

yebdmbv4  于 2023-06-22  发布在  Ruby
关注(0)|答案(1)|浏览(81)

我正在进行Ruby练习,目前无法完成最后一步,即返回当前余额达到目标余额所需的年数。我试过使用while和until(正如练习所暗示的那样),但我没有得到年数。我知道使用until不会返回值,但我正在努力解决如何产生所需的数字。有人能给我指个方向吗?任何帮助将不胜感激!
代码如下:

module SavingsAccount
   def self.interest_rate(balance)
    if balance >= 0 && balance < 1000
      interest_rate = 0.5
    elsif balance >= 1000 && balance < 5000
      interest_rate = 1.621
    elsif balance >= 5000
      interest_rate = 2.475
    elsif balance < 0
      interest_rate = 3.213
    else 
      interest_rate = 0.500
    end
    return interest_rate
    raise 'Please implement the SavingsAccount.interest_rate method'
  end

  def self.annual_balance_update(balance)
    interest_rate = interest_rate(balance) / 100
    interest_rate += 1
    if balance < 0
      return balance * (interest_rate)
    else
      return balance.abs * (interest_rate)
    end
    raise 'Please implement the SavingsAccount.annual_balance_update method'
  end

  def self.years_before_desired_balance(current_balance, desired_balance)
    interest_rate = interest_rate(current_balance) / 100
    interest_rate += 1
    years = 0
    until current_balance == desired_balance do
      current_balance = current_balance * interest_rate
      years += 1
      if current_balance == desired_balance
        return years
      end
    end
    raise 'Please implement the SavingsAccount.years_before_desired_balance method'
  end
end

我已经检查了值,直到“until”关键字被使用,一切看起来正常。我还尝试将“返回年份”行移出until块。
我试图解决的问题是:
实现SavingsAccount. years_before_desired_balance方法来计算达到所需余额所需的最小年数:

SavingsAccount.years_before_desired_balance(200.75, 214.88)
#=> 14

我已经检查了值,直到“until”关键字被使用,一切看起来正常。我还试着把“返回年份”这一行从直到块中移出。我希望返回一个整数,表示当前余额达到基于利率的目标余额所需的年数。

3b6akqbq

3b6akqbq1#

由于floating point numbers work在计算机中的方式,使用==几乎永远不会达到您想要的效果。此外,由于您正在寻找一个 mininum 数字,而不是 exact,您可能希望使用>而不是==
这是你需要的条件:

if current_balance >= desired_balance

请注意,出于同样的原因,until条件永远不会触发,因此您可以使用loop do

相关问题