Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以在C中小数点后打印用户定义精度的浮点?_C_Floating Point Precision - Fatal编程技术网

是否可以在C中小数点后打印用户定义精度的浮点?

是否可以在C中小数点后打印用户定义精度的浮点?,c,floating-point-precision,C,Floating Point Precision,我想在C中的小数点后打印出一个用户定义精度的浮点,比如 int dec; float no; printf("\nEnter no of decimal places and the number "); scanf("%d%f",&dec,&no); 然后打印数字no和dec小数位。Do int dec; float no; printf("\nEnter no of decimal places and the number "); scanf("%d%f",&de

我想在C中的小数点后打印出一个用户定义精度的浮点,比如

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
然后打印数字
no
dec
小数位。

Do

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
printf("%.*f",dec,no);

您可以格式化浮点数的打印,但不能格式化其实际大小

您可以阅读有关格式化浮点数的内容

为了节省时间,您可以使用%f格式说明符,如下所示

printf("%.PRECISIONf", fvar);
其中精度是小数点后所需的位数,例如

int 
print_float(float fvar, unsigned int precision) {
  char fs[32];
  sprintf(fs,"%%.%df", precision);
  return printf(fs, fvar);
}
调用例程时:

print_float(2.0f, 2);
您将得到2.00作为输出


希望这能解决您的问题。

如果您知道答案,为什么要发布这个问题?@chrisdd:我确实使用了
printf(“%.*f”,dec,no”)设置了要打印的小数位数的格式
where
dec
存储要打印的小数位数。@nisargshah95您有需要的吗?我已经更新了答案。是的。我将其作为答案发布。您的代码给了我错误-
警告:转换在
sprintf(fs,\%.%df),precision行的格式[-Wformat=]末尾缺少类型
@nisargshah95我已经修复了这个问题,有一个小的打字错误,我想说的是,这不是最好的代码,它只是方向性的。