我有一個關於我的代碼的問題。我知道我需要在代碼中改變什麼,但是我想明白爲什麼會發生這種情況,因爲我真的想學習基礎知識。所以我的代碼是:while while循環中兩個條件之間的區別
public class chunnimunni {
public static void main(String[] args) {
double number = 2.0;
while (true) {
if (number == 0.5)
break;
number -= 0.1;
System.out.printf("%8.1f", number);
}
System.out.println ("Finished.");
}
}
這段代碼將繼續並無限期地打印出數字,它不會停在0.5。但是,如果我從改變而條件:
while (true)
到
while (number > 0.5)
然後它工作。
如果有人能解釋這個原因,我會非常高興。謝謝。
而不是'System.out.printf(「%8.1f」,number);''使用'System.out.println(number);'你會看到更精確的值被'號碼'0.49999999999999933'不等於'0.5'所以'if(number == 0.5)break;'永遠不會發生。更多在此[在浮點數學是否壞了?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Pshemo