问题问“编写一个程序,该程序读取初始投资余额和利率,然后打印投资达到一百万美元所需的年数。”
/*
Question: Write a program that reads an initial
investment balance and an interest rate, then
prints the number of years it takes for the
investment to reach one million dollars.
*/
#include <iostream>
using namespace std;
int main()
{
//Obtain user amount
double amount;
cout << "Please enter an initial investment balance ($0.00): $";
cin >> amount;
//Obtain user interest rate
double interest_rate;
cout << "Please enter an interest rate: ";
cin >> interest_rate;
//Convert interest rate to decimal
interest_rate = interest_rate / 100;
int time = 1;
//Calculate how many years
while (amount < 1000000)
{
amount = amount * (1 + (interest_rate * time));
++time;
}
//Display years
cout << "Years to reach one million: " << time;
return 0;
}
我期望的输出是:
因为333300恰好是一百万。
答案 0 :(得分:7)
一年后,金额将增加到
amount * (1 + interest_rate)
在两年内,数量增长到
amount * (1 + interest_rate) * (1 + interest_rate)
假设您的利率每年复利。您包含time
以及与amount
的连续乘法都是错误的。
请注意,存在封闭形式的解决方案。对于费率 r ,初始金额 I ,最终金额 A ,年份 t 为
t = ln( A / I )/ ln(1 + r )
您需要四舍五入。