首页 > 解决方案 > 在 C 中将浮点数舍入到用户指定的小数位数

问题描述

如问题所示,如何将浮点数四舍五入到用户指定的小数点位数?我当前的代码仅将浮点数打印到小数点后 2 位。另外,是否有用于此目的的内置功能?

#include <stdio.h>

int main()
{
    float x = 1.2345;
    int dp;
    printf("The float is: %f. How many decimal points to round to? ", x);
    scanf("%d", &dp);
    printf("Number: %.2f", x);
}

标签: cfloating-pointrounding

解决方案


您可以用*字符代替精度,在这种情况下,下一个参数将指定精度。

printf("Number: %.*f", dp, x);

推荐阅读