Hi everyone! I have a question about computing compound interest.
What I'm trying to do is display all of the years and their total deposit amounts, depending on the number the user inputs for the years. So if the user inputs 5 for the amount of years, I want the output to show years 1 - 5 and their deposit amounts. How would I be able to do that?
Here's my code (Getting the user's inputs are in a separate file, this is where I'm doing the calculation and displaying):
(1) If you want the years to go forward ... then start with 1 and count UP, not down!
(2) DON'T use pow(). Simply set totalAmount=principal before the loop and multiply totalAmount by ( 1 + interestRate / 100) once on each pass through the loop. After all, that's what the bank does!
(3) If you want to output the year then output the loop index, NOT 1, every time.
(4) Choose a counter-type name, like i or n, for the loop index, not year1, which is rather close to an existing variable.
When I try to count up, it starts at what the user inputs.
So for example if the user inputs 5, it will start from 5 and count up. Not only that, but it will increase infinitely
#include <iostream>
#include <iomanip>
usingnamespace std;
double Compute_Investment(double principal, double interestRate, int years)
{
for (int n = 1, i = years; n = i; n++, i++) //CHANGED HERE
{
double totalAmount;
totalAmount = principal * pow((1 + interestRate / 100), n);
cout << endl;
cout << "Years" << setw(25) << "Amount of Deposit" << endl;
cout << setprecision(2) << fixed;
cout << setw(4) << n << setw(10) << totalAmount;
}
cout << endl;
return 0;
}
The output:
Years Amount of Deposit
5 1276.28
Years Amount of Deposit
6 1340.10
Years Amount of Deposit
7 1407.10
Years Amount of Deposit
8 1477.46
Years Amount of Deposit
9 1551.33
Years Amount of Deposit
10 1628.89
Years Amount of Deposit
11 1710.34
Years Amount of Deposit
12 1795.86
Years Amount of Deposit
13 1885.65
Years Amount of Deposit
14 1979.93
Years Amount of Deposit
15 2078.93
Years Amount of Deposit
16 2182.87
etc...
Initialise totalAmount to the principal before the loop.
Don't use pow(). Read my previous post.
I've no idea why you have BOTH n and i, or how they got so confused. Start with n=1 and loop while n<= years. If n is your loop index then i isn't needed.
Are you sure that you're not yet another incarnation of Rascake?