我正在使用一個教程編寫一個簡單的應用程序,計算一個銀行賬戶需要多少年才能達到目標金額。如果陳述不在C#中工作
我試圖使用「If」語句,因此如果人的起始餘額大於其目標金額,則會打印出「您的餘額大於目標金額」,但是當我將其寫入代碼時,無論用戶輸入多少,它總是打印上面的內容。
下面的代碼:
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
什麼是調試器告訴你,當你通過代碼? –
我添加了大括號,因爲有一個不必要的換行符。 –