I'm currently learning c++ on a linux machine. I've got the following code for rounding down or up accordingly but only whole numbers. How would I change this code to round to the hundredths place or any other decimal? I wouldn't ask if I didn't try looking everywhere already :( and some answers seem to have a ton of lines for what seems to be a simple function!
double round( double ){
return floor(value + 0.5 );
}
Try
double round( double value )
{
return floor( value*100 + 0.5 )/100;
}
to round to two decimal places.
To do it generically, use the same function you've got, but shift the input up or down some decimals:
double round( double value, int precision )
{
const int adjustment = pow(10,precision);
return floor( value*(adjustment) + 0.5 )/adjustment;
}
(Note that you'll have to #include <math.h>
or #include <cmath>
to use the pow function. If you want to write out a (less powerful) pow for this situation, you could try somrething like:
int intpow(int value, int power)
{
int r = 1;
for (int i=0; i<power; ++i) r *= value;
return r;
}
[EDIT @ Ben Voigt's comment] only calculated the adjustment once.
精彩评论