0
cout << setprecision (2) << fixed;
cin>>R;
cout<<R;

Now if I set R = 2.3456, this gives me 2.34. But in calculation R works as 2.3456 if i take this number as input. But I want to take 2.34 as input after doing precision. How do i do that?

  • Your precision works on the output, not input. That is why the value is still present in "full" precision. – Yunnosch Nov 19 '17 at 08:52
  • You could multiply by 100, floor it, divide by 100 and then go on, but be warned of https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Yunnosch Nov 19 '17 at 08:53

2 Answers2

1

There's no way to take input with a specific precision. Stuffs like std::setprecision only works on output streams. You can manually "truncate" extra precision by rounding.

This is an example:

double a;
std::cin >> a;
a = std::round(a * 100.0) / 100.0;

Be ware that decimal floating points may not be represented percisely in computers.

iBug
  • 35,554
  • 7
  • 89
  • 134
1

I think the more general method would be :

#include <math.h>

double roundTo( double inNumber, int n ) {
   double nn = pow( 10, n );
   // static_cast< dest_type > is more modern and standard way ..
   return static_cast<double>( static_cast<long long>( inNumber * nn ) / nn );
}
nullqube
  • 2,959
  • 19
  • 18