以下代码有什么问题?

时间:2011-01-24 21:52:21

标签: c

//计算n年后银行账户中的金额

的程序
#include <stdio.h>

double bank(double money, double apy, int years);

int main() {

double money1, apy1;
int years1;

printf("How much money is currently in your bank account? ");
scanf("%d", &money1);

printf("How many years will this money stay in your account? ");
scanf("%d",&years1); 

printf("What is your APY? ");
scanf("%d", &apy1); 

int bank1 = bank(money1, apy1, years1);

printf("Your grand total after %d will be $%d \n", years1, bank1); 


system ("PAUSE");
return 0;   
}


double bank(double money, double apy, int years) {

 if(years <= 0) 
    return money;

 else
    return bank(money*apy, apy, years-1);

 }

5 个答案:

答案 0 :(得分:4)

此:

return bank(money*apy, apy, years-1);

应该是

return bank(money*(1+apy), apy, years-1);

因为您获得的利息应该加到现有金额中。否则你的总金额会每年减少。

答案 1 :(得分:4)

变化:

scanf("%d", &money1);

scanf("%lf", &money1);

并改变:

scanf("%d", &apy1); 

为:

scanf("%lf", &apy1); 

当你在它时,你可能想添加一些printfs来帮助调试(假设你没有源代码级调试器。)

答案 2 :(得分:2)

另一个是:

double bank(double money, double apy, int years);

返回双精度

int bank1 = bank(money1, apy1, years1);

将结果放在int。

答案 3 :(得分:1)

You should never use floating point in financial calculations.

浮点本质上无法精确地表示10个基本值,这意味着您将遭受舍入误差和不等式,这在财务(等等)中是不可接受的。

This has been discussed in detail many times on SO。问题不是语言特定的。

答案 4 :(得分:0)

我认为你应该按照以下方式给你打电话:

int bank1 = bank(money1, 1+apy1/100., years1);

否则你会有很多钱:)