double a = 0;
double b = -42;
double result = a * b;
cout << result;
Run Code Online (Sandbox Code Playgroud)
结果a * b是-0,但我预料到了0.我哪里做错了?
Naw*_*waz 31
该位表示的-0.0和0.0是不同的,但它们是相同的值,那么-0.0==0.0将返回true.在你的情况,result是-0.0因为操作数之一为负.
看这个演示:
#include <iostream>
#include <iomanip>
void print_bytes(char const *name, double d)
{
unsigned char *pd = reinterpret_cast<unsigned char*>(&d);
std::cout << name << " = " << std::setw(2) << d << " => ";
for(int i = 0 ; i < sizeof(d) ; ++i)
std::cout << std::setw(-3) << (unsigned)pd[i] << " ";
std::cout << std::endl;
}
#define print_bytes_of(a) print_bytes(#a, a)
int main()
{
double a = 0.0;
double b = -0.0;
std::cout << "Value comparison" << std::endl;
std::cout << "(a==b) => " << (a==b) <<std::endl;
std::cout << "(a!=b) => " << (a!=b) <<std::endl;
std::cout << "\nValue representation" << std::endl;
print_bytes_of(a);
print_bytes_of(b);
}
Run Code Online (Sandbox Code Playgroud)
输出(demo @ ideone):
Value comparison
(a==b) => 1
(a!=b) => 0
Value representation
a = 0 => 0 0 0 0 0 0 0 0
b = -0 => 0 0 0 0 0 0 0 128
Run Code Online (Sandbox Code Playgroud)
正如你可以看到自己的最后一个字节-0.0是从不同的最后一个字节0.0.
希望有所帮助.