1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cmath>
using namespace std;
double roundDouble1( double x, int n )
{
stringstream ss;
ss << scientific << setprecision( n - 1 ) << x;
return stod( ss.str() );
}
double roundDouble2( double x, int n )
{
int shift = 0;
bool neg = false;
if (x < 0.0) {
x = -x;
neg = true;
}
// normalize
for ( ; x < 1.0; --shift) x *= 10;
for ( ; x >= 1.0; ++shift) x /= 10;
// shift
for ( ; n > 0; --n, --shift) x *= 10;
// round
x = round(x);
// adjust
for ( ; shift > 0; --shift) x *= 10;
for ( ; shift < 0; ++shift) x /= 10;
return neg ? -x : x;
}
int main()
{
cout << roundDouble1( 655900.0, 3 ) << " " << roundDouble1( 433.72, 3 ) << '\n';
cout << roundDouble2( 655900.0, 3 ) << " " << roundDouble2( 433.72, 3 ) << '\n';
cout << roundDouble1( 1.0, 3 ) << " " << roundDouble1( 0.0072123, 3 ) << '\n';
cout << roundDouble2( 1.0, 3 ) << " " << roundDouble2( 0.0072123, 3 ) << '\n';
cout << roundDouble1( -655900.0, 3 ) << " " << roundDouble1( -433.72, 3 ) << '\n';
cout << roundDouble2( -655900.0, 3 ) << " " << roundDouble2( -433.72, 3 ) << '\n';
cout << roundDouble1( -1.0, 3 ) << " " << roundDouble1( -0.0072123, 3 ) << '\n';
cout << roundDouble2( -1.0, 3 ) << " " << roundDouble2( -0.0072123, 3 ) << '\n';
}
|