【问题标题】:Solving a C# interest problem, how do you calculate the number of years it takes a savings balance to reach its intended target balance?解决 C# 利息问题,如何计算储蓄余额达到预期目标余额所需的年数?
【发布时间】:2021-11-08 07:40:13
【问题描述】:

说明

在本练习中,您将使用储蓄账户。每年,您的储蓄账户的余额都会根据其利率进行更新。您的银行给您的利率取决于您帐户中的金额(余额):

  • 3.213% 为负余额。
  • 0.5% 的正余额小于 1000 美元。
  • 对于大于或等于 1000 美元且小于 5000 美元的正余额为 1.621%。
  • 大于或等于 5000 美元的正余额为 2.475%。

你有三个任务,每个任务都会处理你的余额及其 利率。

我解决了前两个任务,要求根据指定余额计算利率,然后根据利率计算年度余额更新。

第三个任务问这个:

实现(静态)SavingsAccount.YearsBeforeDesiredBalance() 方法来计算达到所需余额所需的最小年数:

示例:

SavingsAccount.YearsBeforeDesiredBalance (balance: 200.75m, targetBalance: 214.88m)

输出// 14


到目前为止,我的代码余额超过 5000 美元:

public static int YearsBeforeDesiredBalance(decimal balance, decimal targetBalance)
{
    while ( balance <= targetBalance && targetBalance >5000 )
    {
        return  (int)((0.02475m * balance ) + balance);
        balance ++;
    }
}

我假设我必须找到一种方法来计算此 while 循环执行的次数,但是我不知道该怎么做。任何指导将不胜感激。

【问题讨论】:

  • a) 你在循环中有一个return,所以它只会“循环”一次。 b)您只需要另一个 vr 来计算迭代count++ c)您在每个循环(年???)都向天平添加一块金子,这可能是不正确的。但按照这个速度,需要很多年。

标签: c# while-loop


【解决方案1】:

您必须利用您已经定义了以下方法:

decimal CalculateTheInterestRateBasedOnTheSpecifiedBalance(decimal balance) { }
decimal CalculateTheAnnualBalanceUpdateTakingIntoAccountTheInterestRate(decimal balance, decimal interestRate) { }

然后就变得简单了:

public static int YearsBeforeDesiredBalance(decimal balance, decimal targetBalance)
{
    if (balance <= 0) throw new ArgumentOutOfRangeException("Balance cannot be less than or equal to zero.");
    if (targetBalance < 0) throw new ArgumentOutOfRangeException("Target Balance cannot be less than to zero."); /* Yes, only `<` */ 
    int years = 0;
    while (balance < targetBalance)
    {
        decimal interestRate = CalculateTheInterestRateBasedOnTheSpecifiedBalance(balance);
        balance = CalculateTheAnnualBalanceUpdateTakingIntoAccountTheInterestRate(balance, interestRate);
        years++;
    }
    return years;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多