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?
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?
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.
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 );
}