简体   繁体   English

C ++不能截断双打吗?

[英]C++ not truncating doubles?

My code : 我的代码

The result of running the following code: 运行以下代码的结果:

#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;
}

Is: 是:

float: 4.19999980926513671875
0    10000001 00001100110011001100110

double: 4.20000000000000017763568394002504646778106689453125
0 10000000001 0000110011001100110011001100110011001100110011001101

Notice how I set both f and d to 4.2, but the float value is slightly less than 4.2 and the double value is slightly more than 4.2. 注意如何将fd都设置为4.2,但float值略小于4.2,double值略大于4.2。 I understand why the float value is less than 4.2; 我理解为什么float值小于4.2;为什么? the 4.2 value gets truncated to a value ~2^-21 less than 4.2. 4.2的值将被截断为小于4.2的〜2 ^ -21值。 However, I don't understand why the double value is slightly greater than 4.2. 不过,我不明白为什么双值大于4.2 稍大 I thought that float and double values would just truncate, but it seems that the double value is rounding up rather than down. 我以为float和double值会截断,但double值是向上取整而不是向下取整。

In general, do floats and doubles round to the nearest representable value? 通常,浮点数和双精度数是否舍入到最接近的可表示值? Do floats and doubles round differently? 浮球和双打有不同的回合吗? I've tried searching for this but couldn't find anything relevant. 我尝试搜索此内容,但找不到任何相关内容。

Floating point values are not truncated , they're rounded to the nearest representable value. 浮点值不会被截断 ,而是四舍五入为最接近的可表示值。 You've discovered an interesting example where the rounding goes in a different direction depending on the size of the floating point, but this is not uncommon; 您发现了一个有趣的示例,其中根据浮点的大小四舍五入的方向不同,但这并不罕见。 you can expect the rounding to go up about 50% of the time and down 50% of the time, with some small number of values being exactly representable and not rounded at all. 您可以预计,舍入的时间大约会增加50%,而舍入的时间会减少50%,其中少量的值可以精确表示并且完全不舍入。 For example 4.25 would be exact. 例如4.25将是准确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM