我被这个问题困住了。
我在一些变量中得到双值,如下所示:
a = 0.76271469999999997000
b = 0.66698279999999999000
c = 0.34262199999999998000
我需要将这些四舍五入
rounded_a = 0.762714700000000
rounded_b = 0.666982800000000
rounded_c = 0.342622000000000
我该怎么做呢?
#include <stdio.h>
#include <math.h>
double round_n(double x, int n){
double wk;
wk = pow(10.0, (double)n);
return round(x * wk)/wk;//c99 function
}
int main(void){
double a, b, c;
a = 0.76271469999999997000;
b = 0.66698279999999999000;
c = 0.34262199999999998000;
a = round_n(a, 7);
b = round_n(b, 7);
c = round_n(c, 7);
printf("a=%.8lf\nb=%.8lf\nc=%.8lf", a, b, c);
return 0;
}
这是我使用的代码:
int64_t __pow10_arr[18] = { 1l, 10l, 100l, 1000l, 10000l, 100000l,
1000000l, 10000000, 100000000l, 1000000000l, 10000000000l, 100000000000l,
1000000000000l, 10000000000000l, 100000000000000l, 1000000000000000l, 10000000000000000l, 100000000000000000l };
double roundToNfractions ( double val, int n )
{
if (n<0 || n >= ( sizeof (__pow10_arr)/ sizeof (int64_t) ) ) {
// log error however you wish to
return val;
}
val *= __pow10_arr[n];
val += 0.5;
val = (uint64_t) val;
val /= __pow10_arr[n];
return val;
}