簡體   English   中英

WHILE循環中的布爾語句沒有意義嗎?

[英]Boolean Statement in WHILE loop doesn't make sense?

我的while聲明對我來說似乎沒有任何意義,即使它可行。
我希望它在countYears 小於 timeLimit的情況下計算利息。...因此,如果將timeLimit設置為5,則它應該僅計算5年的利息,但以我讀取當前while語句的方式,似乎沒有這么說。 也許我只是讀錯了?

public class RandomPractice {
public static void main(String[] args)
{
    Scanner Keyboard = new Scanner(System.in);
    double intRate, begBalance, balance;
    int countYears, timeLimit;

    System.out.println("Please enter your current investment balance.");
    begBalance = Keyboard.nextDouble();

    System.out.println("Please enter your YEARLY interest rate (in decimals).");
    intRate = Keyboard.nextDouble();

    System.out.println("Please enter how long (in years) you would like to let interest accrue.");
    timeLimit = Keyboard.nextInt();

    balance = begBalance * (1 + intRate);
    countYears = 0;

    /* The way I read this while statement is as follows 
     * "While countYears is GREATER than the timeLimit...calculate the balance"
     * This makes no logical sense to me but I get the correct output? 
     * I want this code to calculate the investment interest ONLY as long as
     * countYears is LESS than timeLimit **/
    while (countYears >= timeLimit)
    {
        balance = balance + (balance * intRate);
        countYears++;
    }       

    System.out.println(balance);

  }
}

您所擁有的代碼無法生成正確的數據,我的成績單以每年1%的速度記錄了八年:

Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0

換句話說,只增加一年的利息,而不是八年。

因此,或者您的編譯器完全是搞砸了,您的代碼不是您想像的那樣,或者您用來檢查興趣度計算的任何測試數據和/或方法都有些缺乏。

首先,正如您所countYears < timeLimit那樣,您需要將條件更改為countYears < timeLimit

此外,您還需要在循環之前刪除初始利息計算因為這意味着您存入錢后將獲得全年的利息。 有了這兩個更改:

balance = begBalance;
while (countYears < timeLimit) {
    balance = balance + (balance * intRate);
    countYears++;
}       

然后您將獲得正確的值

Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801

如果將循環切換為<= ,則根本不會執行循環,這是正確的。

現在,您的輸出是在循環外部計算的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM