-2

在您 21 岁生日时,您的祖母会为您开设一个储蓄账户并存入 1000 美元。储蓄账户对账户余额支付 3% 的利息。如果您不再向账户中存入资金,并且您不再从账户中提取任何资金,那么您的储蓄账户在 1 到 5 年末的价值是多少?

创建一个为您提供答案的程序。您可以使用以下公式计算答案: b = p * (1 + r)n 。在公式中,p 是本金(存款金额),r 是年利率(3%),n 是年数(1 到 5),b 是储蓄账户中的余额第 n 年年底。使用 for 循环。

任何帮助将不胜感激

这就是我到目前为止所拥有的,我得到的只是一个无限循环

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

void main()
{
// Inputs //

double princ = 0.0;
double rate = 0.0;
int years = 0;
int year = 1;
double total = 0.0;

// Ask User For INFO //

cout << "What is the principle? ";
cin >> princ;
cout << "What is the rate in decimal? ";
cin >> rate;
cout << "how many years? ";
cin >> years;



for (double total; total = princ*(1+rate)*year;)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

while((years + 1)!= year);

system("pause");
}
4

2 回答 2

1

您误解了 for 循环的工作原理。它用于做某事一定次数,在您的示例中,循环一定年数是合适的。像这样的东西:

double interest = 1.0 * rate:
double accumulated = 1.0 * interest;

for (auto i=1; i < years; ++i) {
    accumulated *= interest;
    cout << "The balance after year " << i << " is " << (princ * accumulated) << std::endl;
}
于 2013-10-26T00:29:19.870 回答
0

你的问题是你以某种方式混淆了你的forwhile循环。

代替

for (double total; total = princ*(1+rate)*year;)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

while((years + 1)!= year);

你可能想要这样的东西:

for (double total; (years +1) != year; total = princ*(1+rate)*year)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

此外,您的main函数不应该void像评论中已经指出的那样返回,而应该是int main()

于 2013-10-26T00:21:08.097 回答