I’m using a tutorial to write a simple app that calculates how many years it will take for a bank account to reach a target amount.
I’m trying to use an “If” statement, so if the person’s beginning balance is more than their target amount, it prints “Your balance is bigger than the target amount”, but when I write this into my code, it always prints the above no matter what amounts the user inputs.
Here’s the code:
double balance, interestRate, targetBalance; //creating three doubles
Console.WriteLine("What is your current balance?"); //writing to the console
balance = Convert.ToDouble(Console.ReadLine()); //reading what the user inputs & converting it to a double
Console.WriteLine("What is your current annual interest (in %)?");
interestRate = 1 + Convert.ToDouble(Console.ReadLine()); //same as above
Console.WriteLine("What balanec would you like to have?");
targetBalance = Convert.ToDouble(Console.ReadLine()); //same as above
int totalYears = 0; //creates an int variable for the total years
do
{
balance *= interestRate; //multiplying balance x interest rate
++totalYears; // adding 1 to the total years
}
while (balance < targetBalance); //only do the above when balance is less than target balance
if (balance < targetBalance)
{
Console.WriteLine("In {0} year{1} you'll have a balance of {2}.", totalYears, totalYears == 1 ? "" : "s", balance); //writing the results to the console
}
else if (targetBalance < balance)
{
Console.WriteLine("Your balance is bigger than the target amount");
}
Console.ReadKey(); //leaving the results there until the user inputs a key
The only way for your
do-whileloop to exit is when the balance is>=the target balance. Because of this, your firstifstatement will never evaluate totrue.You probably want to do your
targetBalance < balancecheck before you enter yourdo-whileloop. If the balance is greater than the target, start over. And then after the loop, there is no need to do the if check around your ‘In x years…’ dialog.