【问题标题】:Calculate interest without math library在没有数学库的情况下计算利息
【发布时间】:2017-09-24 04:27:35
【问题描述】:

我试图在没有 math.h 和 pow 的情况下计算租金,不知何故我几乎算对了,但它没有计算正确的金额,我不确定问题可能出在哪里,对我缺少什么有任何建议吗?

#include <stdio.h>

double calcFutureValue(double startingAmount, double interest, int numberOfYears);

int main() {

    double startMoney, interest, futureMoney;
    int years;

    printf("Enter amount of money: ");
    scanf("%lf", &startMoney);
    getchar();

    printf("Enter interest on your money: ");
    scanf("%lf", &interest);
    getchar();

    printf("Enter amount of years: ");
    scanf("%d", &years);
    getchar();


    futureMoney = calcFutureValue(startMoney, interest, years);

    printf("In %d years you will have %.1f", years, futureMoney);
    getchar();

    return 0;
}

double calcFutureValue(double startingAmount, double interest, int numberOfYears) {

    double totalAmount;
    double interest2 = 1;


    for (int i = 0; i < numberOfYears; i++)
    {
        interest2 += interest / 100;
        totalAmount = startingAmount * interest2;
        printf("%lf", totalAmount);
        getchar();

     }

     return totalAmount;
 }

【问题讨论】:

    标签: function input double output calculation


    【解决方案1】:

    您的计算中不是compounding the interest

    根据你的职能,interest2 += interest / 100

    这意味着对于 10% 的利息,您将拥有:

    0 : 1
    1 : 1.1
    2 : 1.2
    3 : 1.3
    

    但在复利情况下,利息适用于先前赚取的利息以及本金:

    0 : 1
    1 : 1.1
    2 : 1.21
    3 : 1.331
    

    试试这样的:

    interest2 = 1 + interest / 100.0;
    totalAmount = startingAmount;
    
    while (numberOfYears--) {
        totalAmount *= interest2;
    }
    

    【讨论】:

    • Austin 我尝试了您提供的解决方案,但似乎不起作用,我删除了 for 循环并将其替换为 while 循环示例。
    • 你初始化totalAmount了吗?已更新。
    • 是的,正如你在上面写的那样。
    • 你得到了什么结果?
    • 如果我输入金额:10000 利息:8 年数:3 它打印出 800.00000 64.000000 5.120000 在 3 年内你将有 5.1 我有返回总金额;在函数的末尾。
    【解决方案2】:

    非常感谢,我总是很高兴获得不同的观点,但当我添加这个时我发现它起作用了:

    double calcFutureValue(double startingAmount, double interest, int numberOfYears) {
    
        double totalAmount;
        double interest2 = 1;
        double random3 = 1 + interest / 100;
    
    
        for (int i = 0; i < numberOfYears; i++)
        {
            interest2 *= random3;
            totalAmount = startingAmount * interest2;
            printf("%lf", totalAmount);
            getchar();
    
        }
    
        return totalAmount;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2016-07-27
      • 2013-10-30
      • 1970-01-01
      相关资源
      最近更新 更多