C ++,兴趣计算器未显示正确的输出

时间:2019-05-24 12:05:59

标签: c++

问题问“编写一个程序,该程序读取初始投资余额和利率,然后打印投资达到一百万美元所需的年数。”

  • 我输入的金额为100,利率为3。但是,当我编译并运行时,输出为29,这是不正确的,因为数量仅为187,根本不接近一百万。
/*
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;
}

我期望的输出是:

“达到100万的年份:333300”

因为333300恰好是一百万。

1 个答案:

答案 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

您需要四舍五入。