编写一个函数,可以按照指定小数位对实数进行四舍五入。如对于5.23682,如果指定小数位为1位,结果是5.2;如果指定小数位为2位,结果为5.24。

为什么结果一直都是小数点后7位,而且还多了两行数字(0.000000 6749900),这个程序应该怎么更改,求解

100.456001.toFixed(2); // 100.46
100.456001.toFixed(3); // 100.456

该回答引用chatgpt:


#include <math.h>
#include <stdio.h>

double round_to_n_decimal_places(double num, int n) {
    double factor = pow(10, n);
    double rounded_num = round(num * factor) / factor;
    return rounded_num;
}

int main() {
    double num = 5.23682;
    int n = 2;
    double rounded_num = round_to_n_decimal_places(num, n);
    printf("%.2f", rounded_num);
    return 0;
}