Cod*_*ter 0 c++ floating-point precision double floating-accuracy
我的代码:
运行以下代码的结果:
#include <cstdio>
//i define printBits elsewhere but that's not relevant to my question
void printBits(const float f);
void printBits(const double f);
int main(int argc, char **argv) {
float f=4.2;
double d=4.2;
printf("float: %20.20f\n",f);
printBits(f);
printf("double: %50.50f\n",d);
printBits(d);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
方法是:
float: 4.19999980926513671875
0 10000001 00001100110011001100110
double: 4.20000000000000017763568394002504646778106689453125
0 10000000001 0000110011001100110011001100110011001100110011001101
Run Code Online (Sandbox Code Playgroud)
注意我是如何设置都f和d4.2,但浮点值略小于4.2和双值略微超过4.2.我理解为什么浮点值小于4.2; 4.2值被截断为小于4.2的值~2 ^ -21.不过,我不明白为什么双值略微大于比4.2.我认为float和double值只会被截断,但似乎双值是向上而不是向下.
一般来说,浮点数和双精度数是否为最接近的可表示值?浮动和双打不同吗?我试过搜索这个,但找不到任何相关的东西.
浮点值不会被截断,它们会四舍五入到最接近的可表示值.你已经发现了一个有趣的例子,根据浮点的大小,舍入方向不同,但这并不罕见; 你可以预期四舍五入的时间会在50%的时间内上升,而在50%的时间里会下降,一些少量的值可以完全表示,而不是四舍五入.例如4.25就是准确的.