C ++中double和float的不同输出 [英] C++ different output in double and float

查看:202
本文介绍了C ++中double和float的不同输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例程序:

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

我得到的输出是:

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.

推荐答案

33.3没有精确的有界二进制表示,因此将其转换为floatdouble会导致舍入.

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

float的尾数为23位,等同于精度的6.92个十进制数字;在那里,您要求打印8位数字,该数字比可用精度更高,因此将显示效果或四舍五入.

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的尾数为52位,相当于15.65个十进制数字; 8位有效数字的打印效果很好,因为您仍在打印良好的数字,不受四舍五入的影响.

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.

为了使我们喜欢的基础10的示例更容易理解:假设您有一个精度为15位数字的十进制数据类型,并且想在其中存储1/3.最好的办法是存储0.333333333333333;它们会将其复制到精度为6位数字的数据类型中:它变为0.333333.

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.

现在,如果您打印第一个带有8个十进制数字的值,您将获得0.33333333,而对于第二个,您将具有0.33333300-因为您已经在转换中丢失了其他数字.

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.

这篇关于C ++中double和float的不同输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆