use*_*936 5 c++ double floating-point-precision
可能重复:
在C++中浮动到二进制
我有一个非常小的双变量,当我打印它时我得到-0.(使用C++).现在为了获得更好的精度,我尝试使用
cout.precision(18); \\i think 18 is the max precision i can get.
cout.setf(ios::fixed,ios::floatfield);
cout<<var;\\var is a double.
Run Code Online (Sandbox Code Playgroud)
但它只写-0.00000000000 ...
我想看看var的确切二进制表示.
换句话说,我想看看在这个var的堆栈存储器/寄存器中写入了什么二进制数.
union myUnion {
double dValue;
uint64_t iValue;
};
myUnion myValue;
myValue.dValue=123.456;
cout << myValue.iValue;
Run Code Online (Sandbox Code Playgroud)
更新:
上面的版本适用于大多数用途,但它假定64位双打.此版本不做任何假设并生成二进制表示:
double someDouble=123.456;
unsigned char rawBytes[sizeof(double)];
memcpy(rawBytes,&someDouble,sizeof(double));
//The C++ standard does not guarantee 8-bit bytes
unsigned char startMask=1;
while (0!=static_cast<unsigned char>(startMask<<1)) {
startMask<<=1;
}
bool hasLeadBit=false; //set this to true if you want to see leading zeros
size_t byteIndex;
for (byteIndex=0;byteIndex<sizeof(double);++byteIndex) {
unsigned char bitMask=startMask;
while (0!=bitMask) {
if (0!=(bitMask&rawBytes[byteIndex])) {
std::cout<<"1";
hasLeadBit=true;
} else if (hasLeadBit) {
std::cout<<"0";
}
bitMask>>=1;
}
}
if (!hasLeadBit) {
std::cout<<"0";
}
Run Code Online (Sandbox Code Playgroud)
按照标准,可以保证这种方式有效:
double d = -0.0;
uint64_t u;
memcpy(&u, &d, sizeof(d));
std::cout << std::hex << u;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13629 次 |
| 最近记录: |