为了您的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");
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您的问题是您以某种方式混淆了for
和while
循环。
而不是
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()