我正在使用教程编写一个简单的应用程序,该应用程序计算银行账户达到目标金额需要多少年。
我正在尝试使用“如果”语句,因此如果此人的初始余额超过其目标金额,则会打印“您的余额大于目标金额”,但是当我将其写入代码时,它总是会打印以上无论用户输入多少。
这是代码:
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