在Java中比较float和int是否安全? [英] Is it safe to compare a float and an int in Java?

查看:401
本文介绍了在Java中比较float和int是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  private static void foo(float n){
if(n> = 1 || n <= 0){
// code
}
}

根据 JLS(5.6.2。Binary Numeric Promotion)如果其中一个参数是 float ,另一个是在比较之前转换为 float
但据我所知,这样的比较将返回true,如果转换的浮点数是二进制相同的原始浮点数。我们怎样才能保证它?

解决方案

是的,你的具体例子很好,因为 0 1 可以精确地表示为 float



请注意,这通常不是真的:有许多大的 int 值不能完全表示为 float 。例如,以下输出 true Ideone )即使2_000_000_001不等于2_000_000_000:

$ p $ import java.util。*;
import java.lang。*;
import java.io. *;

class FloatTest {

private static boolean isTwoBillion(float f){
return f == 2_000_000_000;


public static void main(String [] args){
System.out.println(isTwoBillion(2_000_000_001));


$ b $ / code $ / pre

请注意,与 float double 具有足够的尾数来存储每个32位 int 价值。


Is it safe to compare a float and an integer like this?

private static void foo(float n) {
    if (n >= 1 || n <= 0) {
      // code 
    } 
}

According to the JLS (5.6.2. Binary Numeric Promotion) if one of the parameters is float, the other is converted to float before comparison. But as far as I understand, such a comparison will return true if the converted float is binary identical to the original float. How can we ensure it?

解决方案

Yes, your specific example is fine, since both 0 and 1 can be exactly represented as a float.

Note that this is not true in general: there are many large int values that's can't be represented exactly as a float. For example, the following prints out true (Ideone) even though 2_000_000_001 does not equal 2_000_000_000:

import java.util.*;
import java.lang.*;
import java.io.*;

class FloatTest {

    private static boolean isTwoBillion(float f) {
        return f == 2_000_000_000;
    }

    public static void main (String[] args) {
        System.out.println(isTwoBillion(2_000_000_001));
    }

}

Note that, unlike float, double has wide enough mantissa to store every 32-bit int value.

这篇关于在Java中比较float和int是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆