4
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 need the actual unrounded result.Please suggest.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Vikas
  • 41
  • 1
  • 2

3 Answers3

14

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

std::cout.precision(15);
Drew Hall
  • 28,429
  • 12
  • 61
  • 81
  • Thanks, but the actual problem is, i want to use "c" result for other computation and not just for display. – Vikas Nov 08 '10 at 11:01
  • 8
    @Vikas: read the answer again - you are already getting the precision that you need - you're just getting confused because of the way that you are displaying the value. – Paul R Nov 08 '10 at 11:03
  • 2
    You will get 52 bits of precision but it won't be "exact" due to how floating point arithmetic works. – CashCow Nov 08 '10 at 12:24
1

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.

bjskishore123
  • 6,144
  • 9
  • 44
  • 66
0

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.

jcoffland
  • 5,238
  • 38
  • 43