如果语句不在C#中工作

Abr*_*ham 1 c# if-statement

我正在使用教程编写一个简单的应用程序,用于计算银行帐户达到目标金额所需的时间.

我正在尝试使用"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
Run Code Online (Sandbox Code Playgroud)

nic*_*ild 6

do-while循环退出的唯一方法是当余额是>=目标余额时.因此,您的第一个if语句永远不会评估为true.

您可能希望targetBalance < balance在进入do-while循环之前进行检查.如果余额大于目标,请重新开始.然后在循环之后,没有必要在'In x years ...'对话框中进行if检查.