在 C 中将浮点数舍入为用户指定的小数位数
Rounding a float to user-specified number of decimal places in C
在问题中,如何将浮点数四舍五入到用户指定的小数位数?我当前的代码仅将浮点数打印到小数点后两位。另外,是否有用于此目的的内置函数?
#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);
}
您可以用 *
字符代替精度,在这种情况下,下一个参数将指定精度。
printf("Number: %.*f", dp, x);
在问题中,如何将浮点数四舍五入到用户指定的小数位数?我当前的代码仅将浮点数打印到小数点后两位。另外,是否有用于此目的的内置函数?
#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);
}
您可以用 *
字符代替精度,在这种情况下,下一个参数将指定精度。
printf("Number: %.*f", dp, x);