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

C++, Interest Calculator not displaying correct output

本文关键字:输出 显示 计算器      更新时间:2023-10-16

询问"编写一个读取初始投资余额和利率的程序,然后打印投资达到一百万美元所花费的年数。/p>

  • 我投入的输入为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;
}

我期望的输出是:

"达到一百万的年:333300&quot"

由于333300正好是一百万。

在一年内,金额将增长到

amount * (1 + interest_rate)

和两年后,金额增长到

amount * (1 + interest_rate) * (1 + interest_rate)

假设您的利率年度复合。您包含time,以及amount的连续乘法是错误。

请注意,有一个封闭的形式解决方案。对于速率 r ,初始数量 i ,最终数量 a ,年数 t

t = ln( a / i (/ln(1 r (

您需要汇总。