在我的代碼比較負零(-0.0)的,行爲與正零(0.0)
float f = -0.0; // Negative
並用負零
f == -0.0f
結果相比較將是true
。
但
float f = 0.0; // Positive
與負零
f == -0.0f
還比較,結果將是true
而不是false
爲什麼在兩種情況下會導致是真的嗎?
這裏是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;
}
}
輸出:
==== > -0 // Here print negative zero
true
正如你今天所問的[其他](https://stackoverflow.com/a/45790355/4711812)問題所述:在C++中不存在負數爲零的情況。 – muXXmit2X
爲什麼不是? 沒有「負0」,它只是零。所以當然與0比較的結果是正確的。 – Zinki
https://stackoverflow.com/questions/43086963/is-negative-zero-always-equal-zero – CBroe