0
我正在執行浮點值比較..以及在下面的程序中。這是一個非常基本的..在比較過程中有小數點的一些技巧。 請幫我理解這一點。比較在java中給出意外結果的浮點值
class C
{
public static void main(String args[])
{
Float pi = new Float(3.13999999f);
if (pi > 3.13999999) {
System.out.print("pi is bigger than 3. ");
}
else if (pi < 3.13999999){
System.out.print("pi is less than 3. ");
}
}
}
結果:pi是大於3
然後,我已經從所有三個值
class C
{
public static void main(String args[])
{
Float pi = new Float(3.1399999f);
if (pi > 3.1399999) {
System.out.print("pi is bigger than 3. ");
}
else if (pi < 3.1399999){
System.out.print("pi is less than 3. ");
}
}
}
現在的結果是最後一個數字(9)中除去:圓周率小於3
值得注意的原因。在java中,float是一個單精度64位IEEE 754浮點。這並不意味着要保留精確的小數值,所以總會有誤差。 如果您需要確切的數字或託管的精度,您應該使用BigDecimal。 – lscoughlin