C语言如何将double格式化为小数点后两位?

4

可能是重复问题:
限制浮点精度?

在C语言中,我需要从用户输入的数字中格式化出小数点后2位。

例如:

 float x ; 
 printf("Enter number");

假设用户输入了4.54234635 我需要在整个程序中打印并进行处理: 4.54 提前感谢。
3个回答

17
scanf("%.2f",&x);

我认为那将解决一个问题。


在scanf函数中,您无法指定精度。但是在printf函数中可以这样做。 - jtony

13

完整清单

Integer   display
%d      print as decimal integer
%6d     print as decimal integer, at least 6 characters wide
%f      print as floating point
%6f     print as floating point, at least 6 characters wide
%.2f    print as floating point, 2 characters after decimal point

如果进行所需的修改(scanf("%.2f",&x);是最后一次输入),就能解决你的问题。


你确定最后一个 (%6.2f) 是有效的吗? - orustammanapov
@orustammanapov 我目前已经将其移除。 - Shash

3

使用

scanf("%.2f",&number);

or
printf("%.2f", number);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接