首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查零是正的还是负的?

如何检查零是正的还是负的?
EN

Stack Overflow用户
提问于 2014-03-14 23:20:10
回答 8查看 16.6K关注 0票数 79

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

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

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2014-03-14 23:25:01

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

代码语言:javascript
复制
if (1 / x > 0)
    // +0 here
else
    // -0 here

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

票数 81
EN

Stack Overflow用户

发布于 2014-03-14 23:27:19

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

代码语言:javascript
复制
float f = -0.0f;

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

Stack Overflow用户

发布于 2014-03-14 23:31:24

绝对不是最好的方法。签出函数

代码语言:javascript
复制
Float.floatToRawIntBits(f);

Doku:

代码语言:javascript
复制
/**
 * 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);
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22409102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档