I have an assignment where I need to calculate the amount of money for 2 people where we have 2 different interest rates. I need to display the amount of money that they would have at each of the given age. The issue is that it only prints the final amount which is 60 years old, how do I print the correct amount at the correct age? Here is the code
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}","Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
for(int age=20;age<=60;age =10)
{
double Linda = 1000;
double John = 1000;
for (int year=1;year<=40;year )
{
double retLin = 0.06;
double retJon = 0.015;
Linda = Linda * retLin;
John = John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();
CodePudding user response:
If I figured it right, your desired response is a line of output for each person's balance on each deacde. To do this you only need one iteration in wich balances are increased based on each person's interest rate.
But to calculate the interest rate correctly, it should be added to the balance on every year. So a fixed inner loop of 10 iterations is needed for each decade.
The code is:
double Linda = 1000;
double John = 1000;
double retLin = 0.06;
double retJon = 0.015;
for (int age = 30; age <= 60; age = 10)
{
for (int i = 0; i < 10; i )
{
Linda = Linda * retLin;
John = John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Note that this will not print tha balance on the starting decade (you can simply print the starting values before the loop operations).
CodePudding user response:
I think this is what you need (comments in code):
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}", "Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
// It always is good idea to store info in variables, to give
// them meaning and easily parametrize the code.
var baseAge = 20;
var ageStep = 10;
var finalAge = 60;
// Of course, it would not make sense if you'd have just simple loop
// i = 0, i < limit, i .
for (int age = baseAge; age <= finalAge; age = ageStep)
{
double Linda = 1000;
double John = 1000;
// Here you missed starting point, as it always calculated
// as if we were in first loop - we need account for that.
for (int year = age; year <= 40; year )
{
double retLin = 0.06;
double retJon = 0.015;
Linda = Linda * retLin;
John = John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();