开发者

Double multiplication giving rounded results

double a = 2451550;
double b = .407864;
double c= a*b;
cout<<c;

I was expecting the results to be "999898.9892" but getting "999899". I ne开发者_C百科ed the actual unrounded result.Please suggest.


By default, iostreams output 6 digits of precision. If you want more, you have to ask for it:

std::cout.precision(15);


It can also be done using Manipulator setprecision like below.

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
 double a = 2451550;
 double b = .407864;
 double c= a*b;
 cout<<setprecision(15)<<c;
}

Also, Usage of manipulator will make the code compact.


By default the precision of an std::iostream will show how many digits total to display and by default precision is 6. So, since your number has six digits before the decimal place it will not display any after the decimal.

You can change this behavior with the 'fixed' manipulator. 'precision' then changes to mean the number of digits to display after the decimal which is probably what you were expecting.

To always get four digits after the decimal you can do this:

cout << setprecision(4) << fixed << c;

However, keep in mind that this will always display four digits after the decimal even if they are zeros. There is no simple way to get 'precision' to mean at most x number of digits after the decimal place with std::iostreams.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜