簡體   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