C++ different output in double and float [duplicate]

China☆狼群 提交于 2019-12-13 07:56:49

问题


I have a sample program:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
  float a = 33.30;

  double b = 33.30;

  char a1[1024];
  char b1[1024];

  sprintf(a1, "%0.6f", a);
  sprintf(b1, "%0.6lf", b);

  cout << a1 << endl;
  cout << b1 << endl;

  return 0;
}

The output I am getting is:

33.299999
33.300000

I am getting correct result for double and incorrect for float. I am unable to understand this behavior. Any help would be highly appreciated.


回答1:


33.3 has no exact bounded binary representation, so converting it to float or double incurs in rounding.

float has a 23 bit mantissa, equivalent to 6.92 decimal digits of precision; there you are asking to print 8 digits, which are more than the available precision, and thus will show the effect or the rounding.

double instead has a 52 bit mantissa, which is equivalent to 15.65 decimal digits; the 8 significant digits print holds well, as you are still printing good digits, unaffected by the rounding.


To make an easier to digest example in our beloved base 10: imagine you had a decimal data type with 15 digits of precision, and you want to store 1/3 in it. The best you can do is to store 0.333333333333333; them you copy it into a data type with 6 digits of precision: it becomes 0.333333.

Now, if you print the first value with 8 decimal digits you get 0.33333333, while for the second one you have 0.33333300 - as you already lost the other digits in the conversion.

That is what is happening here, but with binary floating point instead of decimal.




回答2:


Here is a good answer to the difference of float vs. double.

What is the difference between float and double?

By default, any magic number (as 33.30 in your program) is processed as double. when you do float a = 33.30;, an error occurred.



来源:https://stackoverflow.com/questions/49767244/c-different-output-in-double-and-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!