关于C#:scanf-读取时限制小数位

scanf - limit decimal places while reading

我知道如何在printf(%xx)中打印值时限制十进制和整数,在我的场景中,我想在从控制台读取它的lef时实现它。

所以有什么方法可以限制

我在下面尝试过,在编译时不显示任何错误,但始终为0,总是浮点值的小数位数。

1
2
3
4
5
6
float f1;
.
.
scanf("%.3f",&f1);
printf("%3.3f\
"
,f1);


如果您查看文档,它会显示

scanf:

A format specifier for scanf follows this prototype:

%[*][width][length]specifier

并将其与printf:

A format specifier follows this prototype:

%[flags][width][.precision][length]specifier

进行比较,您会发现,没有scanf中的precision字段。所以我想舍入(或强制转换为int以削减数字)是唯一的方法。


f1 = round( f1 * 1000.0 ) / 1000.0scanf无法帮助。顺便说一句,使用double代替float