简体   繁体   中英

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 .

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. It displays false instead. Why?

This happens because floating point arithmetic != real number arithmetic .

When f is assigned 2000000000 , it gets converted to 2.0E9 . Then when you add 50 to 2.0E9 , its value doesn't change. So actually, (f == temp + 50) is true .

If you need to work with large numbers but require precision, you'll have to use something like 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.

(although in your case I don't know why you'd need to use a datatype other than long ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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