简体   繁体   English

一个简单的Java代码,当它被设置为返回true时,它会意外返回false

[英]A simple Java code that returns unexpectedly false while it is intened to return true

The following simple code in Java contains hardly 3 statements that returns unexpectedly false though it looks like that it should 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);
    }
}

The above code should obviously display true on the console but it doesn't. 上面的代码显然应该在控制台上显示为true ,但事实并非如此。 It displays false instead. 它显示为false Why? 为什么?

This happens because floating point arithmetic != real number arithmetic . 这是因为浮点运算!=实数运算

When f is assigned 2000000000 , it gets converted to 2.0E9 . f被分配2000000000 ,它将被转换为2.0E9 Then when you add 50 to 2.0E9 , its value doesn't change. 然后,当您将50添加到2.0E9 ,其值不会更改。 So actually, (f == temp + 50) is true . 实际上, (f == temp + 50)true

If you need to work with large numbers but require precision, you'll have to use something like BigDecimal : 如果你需要使用大数字但需要精度,你将不得不使用类似BigDecimal东西:

long temp = 2000000000;
BigDecimal d = new BigDecimal(temp);

System.out.println(d.compareTo(new BigDecimal(temp+50)) < 0);

Will print true as one would expected. 将按照预期打印出true

(although in your case I don't know why you'd need to use a datatype other than long ). (虽然在你的情况下我不知道为什么你需要使用除long之外的数据类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM