繁体   English   中英

如何检查零是正数还是负数?

[英]How do I check if a zero is positive or negative?

是否可以检查float是正零 (0.0) 还是负零 (-0.0)?

我已将float转换为String并检查第一个char是否为'-' ,但还有其他方法吗?

是的,除以它。 1 / +0.0f+Infinity ,但1 / -0.0f-Infinity 通过简单的比较很容易找出它是哪一个,因此您会得到:

if (1 / x > 0)
    // +0 here
else
    // -0 here

(这假设x只能是两个零之一)

您可以使用Float.floatToIntBits将其转换为int并查看位模式:

float f = -0.0f;

if (Float.floatToIntBits(f) == 0x80000000) {
    System.out.println("Negative zero");
}

绝对不是最好的方法。 签出功能

Float.floatToRawIntBits(f);

独行:

/**
 * Returns a representation of the specified floating-point value
 * according to the IEEE 754 floating-point "single format" bit
 * layout, preserving Not-a-Number (NaN) values.
 *
 * <p>Bit 31 (the bit that is selected by the mask
 * {@code 0x80000000}) represents the sign of the floating-point
 * number.
 ...
 public static native int floatToRawIntBits(float value);

Double.equals在 Java 中区分 ±0.0。 (还有Float.equals 。)

我有点惊讶没有人提到这些,因为在我看来它们比迄今为止给出的任何方法都更清晰!

Math.min使用的方法类似于 Jesper 提出的方法,但更清晰一点:

private static int negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);

float f = -0.0f;
boolean isNegativeZero = (Float.floatToRawIntBits(f) == negativeZeroFloatBits);

当浮点数为负数(包括-0.0-inf )时,它使用与负整数相同的符号位。 这意味着您可以将整数表示与0进行比较,从而无需知道或计算-0.0的整数表示:

if(f == 0.0) {
  if(Float.floatToIntBits(f) < 0) {
    //negative zero
  } else {
    //positive zero
  }
}

这在接受的答案上有一个额外的分支,但我认为它在没有十六进制常量的情况下更具可读性。

如果您的目标只是将 -0 视为负数,则可以省略外部if语句:

if(Float.floatToIntBits(f) < 0) {
  //any negative float, including -0.0 and -inf
} else {
  //any non-negative float, including +0.0, +inf, and NaN
}

对于否定:

new Double(-0.0).equals(new Double(value));

对于阳性:

new Double(0.0).equals(new Double(value));

暂无
暂无

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

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