gpt4 book ai didi

c++ - 为什么我的代码不能正确计算利息?

转载 作者:太空宇宙 更新时间:2023-11-04 12:30:36 25 4
gpt4 key购买 nike

在 C++ 中,我无法获得以下代码来正确计算利息。应该是这样算钱的。

1 : 1000

2 : 2050 (1000(1.05) + 1000)

3 : 3152.5 (2050(1.05) + 1000)

4 : 4310.125 (3152.5(1.05) + 1000)

但是,相反,它会这样计算我的利息。

1 : 1000

2 : 2050

3 : 4310.12

4 : 8142.01

看结果,真不知道是怎么回事。

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main(){
bool done;
char finished;
int numberOfYears;
double accountBalance = 1000;
int i;
const double rateOfInterest = 1.05;
const int yearlyIncome = 1000;
while (!done){
cout << "Enter the number of years you've kept your\n"
<< "money in your bank account." << endl;
cin >> numberOfYears;
for (i = 1; i < numberOfYears; i++){
accountBalance *= rateOfInterest;
accountBalance += yearlyIncome;
}
cout << "Balance = $" << accountBalance << endl;
cout << "If you are finished, enter y, otherwise,\n"
<< "enter any key." << endl;
cin >> finished;
if (finished == 'y' || finished == 'Y') done = true;
}
return 0;
}

最佳答案

问题在于您使用该程序的方式。您不会在每次计算后将 accountBalance 重置为 1000。开始 while 循环后,只需将 double accountBalance=1000; 移动到第一行即可。

关于c++ - 为什么我的代码不能正确计算利息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com