C语言浮点数四舍五入到指定位数 - 代码示例和解释
以下是使用C语言编写的程序,将浮点数四舍五入到十分位、百分位、千分位和万分位后输出:
#include<stdio.h>
int main()
{
double num = 100.453627;
double rounded_tenth = round(num * 10) / 10;
double rounded_hundredth = round(num * 100) / 100;
double rounded_thousandth = round(num * 1000) / 1000;
double rounded_ten_thousandth = round(num * 10000) / 10000;
printf('%.1lf
', rounded_tenth);
printf('%.2lf
', rounded_hundredth);
printf('%.3lf
', rounded_thousandth);
printf('%.4lf
', rounded_ten_thousandth);
return 0;
}
在上述代码中,我们使用了round函数来将浮点数四舍五入到指定的位数。通过将浮点数乘以10的n次方,并使用round函数取整,然后再除以10的n次方,即可将浮点数四舍五入到指定位数。
输出结果为:
100.5
100.45
100.454
100.4536
希望对你有帮助!如果还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/OMI 著作权归作者所有。请勿转载和采集!