scanf - 阅读时限制小数位 [英] scanf - limit decimal places while reading

查看:103
本文介绍了scanf - 阅读时限制小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 printf (%x.x ) 中打印值时限制小数和整数,在我的场景中,我想在从控制台本身读取时实现它.

I know how to limit the decimal and integer while printing values in printf (%x.x ), In my scenario I want to implement that while reading from the console itslef.

那么有没有办法在使用 scanf 函数读取时限制浮点值中的小数位数?

So is there any way to llimit the number of decimals in a floating point value while reading using scanf function?

我在下面试过,编译时没有显示任何错误,但总是得到值 0

I tried below , doesn't show any errors while compiling but get's the value 0 always

float f1;
.
.
scanf("%.3f",&f1);
printf("%3.3f\n",f1);  

推荐答案

如果你查看文档,它会说

If you check the documentation, it says

scanf:

scanf 的格式说明符遵循此原型:

A format specifier for scanf follows this prototype:

%[*][width][length]说明符

并将其与 printf 进行比较:

and compare it to printf:

格式说明符遵循此原型:

A format specifier follows this prototype:

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

你会看到,scanf 中没有 precision 字段.所以我想四舍五入(或转换为 int 来削减数字)是唯一的方法.

You will see, there is no precision field in scanf. So i guess rounding (or casting to int to cut the digits) is the only way.

这篇关于scanf - 阅读时限制小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆