我有一个关于我的代码的问题。我知道我需要在代码中改变什么,但是我想明白为什么会发生这种情况,因为我真的想学习基础知识。所以我的代码是: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