为什么这个双精度值打印为 "-0" ?
Why is this double value printed as "-0"?
double a = 0;
double b = -42;
double result = a * b;
cout << result;
a * b
的结果是-0
,但我期望0
。我哪里做错了?
-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);
}
输出(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
您可以自己看到,-0.0
的最后一个字节与0.0
的最后一个字节不同。
希望对你有帮助。
相关文章:
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 打印双精度的整个非小数部分
- 什么样的 GCC 优化可能会根据是否打印来更改双精度?
- 在 c++ 中使用浮点数、双精度打印十进制
- 双精度未打印出来
- 如何在不丢失第一位数字的情况下打印出双精度值
- 如何在 for 循环内部或外部打印双精度变量
- 使用 cout 以精度 4 打印双倍
- 长双精度在 MinGW 上打印错误
- 对应该返回的双精度变量进行舍入,而不是打印
- 如何打印具有正确有效小数位数的C++双精度
- 在所有声明的双精度但整数结果中打印带有函数的圆的面积,为什么
- 如何在Qt中打印所有小数的双精度
- 以给定精度在给定方向上四舍五入打印双精度
- 我应该使用wsprintf()将双精度打印为宽字符串吗
- C++程序不打印出字符串,但输出双精度值
- 双精度/打印在c++中不能处理14位数字
- 打印Python和c++双精度值时的精度差异
- 为什么这个双精度值打印为 "-0" ?
- 打印双精度到字符串流时如何避免"exponent"格式