【问题标题】:C program displays incorrect resultC 程序显示不正确的结果
【发布时间】:2015-10-07 16:02:23
【问题描述】:

我写了一个程序来计算你需要支付的金额。用户以年为单位输入他们的本金金额、利率和时间段,然后程序给他们未来必须支付的金额。当我运行程序时,最终结果或我需要支付的金额太大或不正确。代码如下:

#include <stdio.h>
int calculation_1(int principal, int rate, int years);

int main(void) {

    int amount1, amount3;
    double amount2, total;

    printf("Investement Calculator \n");
    printf("====================== \n");

    printf("Principal : ");
    scanf("%d", &amount1);

    printf("Annual Rate: ");
    scanf("%lf", &amount2);

    printf("No of Years: ");
    scanf("%d", &amount3);

    total = calculation_1(amount1, amount2, amount3);

    printf("The future value is: $%.2f \n", total);

    return 0;
}

int calculation_1(int principal, int rate, int years) {

    double subtotal,final;

    subtotal = principal * (1 + rate) * years;

    return subtotal;
}

我使用以下值进行了测试:本金为 1000,利率为 0.06,年数为 5 年。最终结果应该是 1338.23 美元,但我得到了 5000.00 美元。这是我用来计算金额的公式:

total = principal * (1 + rate) ^number of years.

我不知道我做错了什么。

【问题讨论】:

  • 您是乘以年数,而不是乘以年数。使用 pow() 函数。
  • 同样rate 应该是double,而不是int
  • @alk:呵呵 - 很好发现 - 现在删除了冒犯的“不”!

标签: c math


【解决方案1】:

您的公式没有正确指定:

subtotal = principal * (1 + rate) * years;

应该是

subtotal = principal * pow((1 + rate),years);

还请查看其他答案 (@ameycu).. 您的数据类型不匹配。

【讨论】:

    【解决方案2】:
    int calculation_1(int principal, int rate, int years) //change 2nd parameter type to double
    

    函数需要 2 个参数作为类型 int 并且您在调用 main 时将其传递给 double-

    total = calculation_1(amount1, amount2, amount3);
       /*  amount2 is declared as double */ 
    

    因此,由于amount2 中的这个小数部分将被丢弃,这可能会导致错误的答案。

    您需要使用函数pow 在公式中使用,以便在您的数学公式中得到这个表达式:

    【讨论】:

    • 在 C 的上下文中使用^ 来表达 power-of 操作至少是模棱两可的。
    • @alk 嗯,是的,它只是一个数学公式。他在程序中试图做的事情是逻辑上的错误。
    • 在 C 中 ^ 是 XOR 运算符。不是每个人都可以将其解析为 power-of
    • @alk 看起来确实更好。谢谢!!
    • 不仅仅是“看起来更好”,这并不重要,更重要的是明确、清晰、易于理解、“故障安全”! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    相关资源
    最近更新 更多