Accountant
Accountant

Reputation: 23

C++, Interest Calculator not displaying correct output

The question asks "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."

/*
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;
}

The output i am expecting is:

"Years to reach one million: 333300"

since 333300 is exactly one million.

Upvotes: 1

Views: 266

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

In one year, the amount will grow to

amount * (1 + interest_rate)

and in two years, the amount grows to

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

assuming annual compounding of your interest rate. Your inclusion of time, and the continuous multiplication by amount are errors.

Note that there is a closed form solution. For rate r, initial amount I, final amount A, the number of years t is

t = ln(A / I) / ln(1 + r)

which you need to round up.

Upvotes: 7

Related Questions