【问题标题】:Compounding Yearly Interest and Taking Out Money on a Yearly Basis每年复利并取出资金
【发布时间】:2020-09-24 01:41:47
【问题描述】:

我正在尝试编写一个程序,其中某人的银行账户中有 2,000,000 美元,他们每年可以从中赚取 7%。但是,这个人每年取出 200,000 美元,我想知道该帐户需要多少年才能清空。我正在使用dollars * pow((1+rate), years) 来计算银行每年有多少钱以及他从中获得的利息。然后,我从中减去200000 * years,以获得一定年数后银行中的总金额。我需要使用while loop,所以请记住这一点。我将它设置为 while (total > 0) 这样当帐户达到 $0 时循环将停止。但由于某种原因,我的代码没有运行。如果有人能帮我解决这个问题,我将不胜感激。

#include<stdio.h>
#include<math.h>

int main()
{
    float dollars = 2000000;
    float rate = 0.07;
    float years = 0;
    float ci, total;

    while (total > 0){
            years++;
        ci = dollars * pow((1+rate), years);
        total = ci - (200000 * years);
    }
    printf("It takes %f years for Frank to empty his account.", years);
    
return 0;
}

【问题讨论】:

  • total 在您第一次使用之前从未设置过。这是未定义的行为。
  • 你的计算没有意义。每年,新值为dollars = dollars * ( 1 + rate ) - 200000
  • @WilliamPursell 没错。但是清空帐户需要一年多的时间,因此我将(200000 * years) 中的年数乘以。
  • @John3136 我应该设置它等于什么?如果我将它设置为等于 0 开始,代码将运行,但输出不会按我想要的那样出现。
  • 可以,但您不需要使用pow。这就是循环正在做的事情。 pow 只是在计算中合并了循环。 (例如,你使用 pow 而不是循环,你不要同时使用两者)

标签: c


【解决方案1】:

您的计算不正确。做吧:

#include<stdio.h>

int main(void)
{
        float dollars = 2000000.0;
        float rate = 0.07;
        int years = 0;

        while( dollars > 0.0 ) {
                years += 1;
                dollars = dollars * (1 + rate) - 200000;
        }
        printf("It takes %d years for Frank to empty his account.\n", years);

        return 0;
} 

但是您可能需要添加一些逻辑来检查余额是否每年都在增加,并参数化这些值。例如:

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char **argv)
{
        float dollars = argc > 1 ? strtod(argv[1], NULL) : 2000000;
        float prev = dollars;
        float rate = argc > 2 ? strtod(argv[2], NULL) : 0.07;
        int years = 0;

        while( dollars > 0 ) {
                years += 1;
                dollars = dollars * (1 + rate) - 200000;
                if( dollars >= prev ) {
                        printf("Balance is increasing\n");
                        return 1;
                }
        }
        printf("It takes %d years for Frank to empty his account.\n", years);

        return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    相关资源
    最近更新 更多