在Java中比较float和int是否安全? [英] Is it safe to compare a float and an int in Java?
问题描述
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
。
请注意,这通常不是真的:有许多大的 请注意,与 Is it safe to compare a float and an integer like this? According to the JLS (5.6.2. Binary Numeric Promotion) if one of the parameters is Yes, your specific example is fine, since both Note that this is not true in general: there are many large Note that, unlike 这篇关于在Java中比较float和int是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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
价值。private static void foo(float n) {
if (n >= 1 || n <= 0) {
// code
}
}
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?0
and 1
can be exactly represented as a float
.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));
}
}
float
, double
has wide enough mantissa to store every 32-bit int
value.