浮点数的符号 [英] Sign of a floating point number
本文介绍了浮点数的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个简单的方法来确定浮点数的符号吗?
Is there an easy way to determine the sign of a floating point number?
我尝试了这个:
#include <iostream>
int main(int argc, char** argv)
{
union
{
float f;
char c[4];
};
f = -0.0f;
std::cout << (c[3] & 0x10000000) << "\n";
std::cin.ignore();
std::cin.get();
return 0;
}
其中(c [3]& 0x10000000)一个负数,但我认为这需要我做假设:
where (c[3] & 0x10000000) gives a value > 0 for a negative number but I think this requires me to make the assumptions that:
- 机器的字节是8位大
- 一个浮点数是4字节大?
- 机器的最高有效位是
最左位(字节顺序)
如果任何假设错误或者我错过了任何错误,请更正我。
Please correct me if any of those assumptions are wrong or if I have missed any.
推荐答案
假设它是一个有效的浮点数(而不是例如NaN):
Assuming it's a valid floating point number (and not, for example, NaN):
float f;
bool is_negative = f < 0;
这是一个练习,让读者找出如何测试一个浮点数是否正。
It is left as an exercise to the reader to figure out how to test whether a floating point number is positive.
这篇关于浮点数的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文