[英]A simple Java code that returns unexpectedly false while it is intened to return true
Java中的以下簡單代碼幾乎不包含3個語句,這些語句意外返回false,盡管看起來它應該返回true 。
package temp;
final public class Main
{
public static void main(String[] args)
{
long temp = 2000000000;
float f=temp;
System.out.println(f<temp+50);
}
}
上面的代碼顯然應該在控制台上顯示為true ,但事實並非如此。 它顯示為false 。 為什么?
這是因為浮點運算!=實數運算 。
當f
被分配2000000000
,它將被轉換為2.0E9
。 然后,當您將50添加到2.0E9
,其值不會更改。 實際上, (f == temp + 50)
是true
。
如果你需要使用大數字但需要精度,你將不得不使用類似BigDecimal
東西:
long temp = 2000000000;
BigDecimal d = new BigDecimal(temp);
System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0);
將按照預期打印出true
。
(雖然在你的情況下我不知道為什么你需要使用除long
之外的數據類型)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.