本文介绍了负零(-0.0)与正零(+0.0)相比的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中,
float f = -0.0; //负数
与负零比较
f == -0.0f
结果将会是 true 。
但是
float f = 0.0; //正数
与负零相比较
f == -0.0f
结果也是 true 而不是 false
=http://coliru.stacked-crooked.com/a/4962a3b70d76a260 =nofollow noreferrer>一个MCVE来测试它(live coliru):
#include< iostream>
int main()
{
float f = -0.0;
std :: cout<<====><< f< std :: endl< std :: endl;
if(f == -0.0f)
{
std :: cout<<true<< std :: endl;
}
else
{
std :: cout<<false<< std :: endl;
输出:
p>
====> -0 //这里打印负零
$ div class =h2_lin>解决方案
C ++中的浮点运算通常是。这个标准与实数集合的数学定义不同。 。这也是定义,这两个表示必须比较等于,所以定义:
+0.0 == -0.0
至于为何如此,请在
In my code,
float f = -0.0; // Negative
and compared with negative zero
f == -0.0f
result will be true.
But
float f = 0.0; // Positive
and compared with negative zero
f == -0.0f
also, result will be true instead of false
Why in both cases result to be true?
Here is a MCVE to test it (live on coliru):
#include <iostream>
int main()
{
float f = -0.0;
std::cout<<"==== > " << f <<std::endl<<std::endl;
if(f == -0.0f)
{
std::cout<<"true"<<std::endl;
}
else
{
std::cout<<"false"<<std::endl;
}
}
Output:
==== > -0 // Here print negative zero
true
解决方案
Floating point arithmetic in C++ is often IEEE-754. This norm differs from the mathematical definition of the real number set.
This norm defines two different representations for the value zero: positive zero and negative zero. It is also defined that those two representations must compare equals, so by definition:
+0.0 == -0.0
As to why it is so, in its paper What Every Computer Scientist Should Know About Floating Point Arithmetic, David Goldberg, 1991-03 (linked in the IEEE-754 page on the IEEE website) writes:
这篇关于负零(-0.0)与正零(+0.0)相比的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!