where should I initialize it and what should I initialize it to? |
I would initialize it right where you define it. So on or around line 24. As to what to initialize it to I would say 0 because you start out with 0 interestEarned.
Though you will still have a problem with your program even after you do that. The reason why is because you have a minor problem in the way your findInterest function works. The problem deals with the equation to find how much interest would be gain.
Lets walk through the loop and one line after it.
1 2 3 4 5 6
|
double totalSaved = invested;
for(int i=1; i <= years; i++)
{
totalSaved += totalSaved * rate;
}
|
So here we initialize the local totalSaved variable to what was passed in the invested parameter. In your example this value = 100.
Next we go through a loop the amount of years worth of interest we want to add. In your example this is 2 years and the rate is 0.1 . On each time through the loop we add the interest to our totalSaved variable. So
Before loop: totalSaved = 100;
Loop 1: totalSaved = 110;
Loop 2: totalSaved = 121;
Now we want to find out how much interest we have earned (I believe this is what you want correct?). What you are doing now is doing this.
interest = totalSaved - interest;
So if we initialized the interestEarned variable to 0 like suggested the equation would be this.
interest = 121 - 0;
As you can see that doesn't seem right. What you want to do instead is compare what the starting investment was (100) to what we have stored in the totalSaved variable (121) and that should give you the total interest that was earned (21).