如何只接受在scanf中的某个precision(这么多的小数位数)? [英] How to only accept a certain precision (so many decimals places) in scanf?

查看:196
本文介绍了如何只接受在scanf中的某个precision(这么多的小数位数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scanf()的的功能,我想只取小数点高达我们values​​.Can实现呢?
例如,对于高达显示我们用小数点后两位的printf(%2F,A)
 我们怎样才能做到这一点对 scanf()的功能。

In scanf() function I want to take only upto decimal values.Can we achieve it? For example for displaying upto two decimal places we use printf("%.2f",A) How can we do it for scanf() function.

推荐答案

您不能这样做,可以使 scanf()的如果读取字符的具体数量你要像

You can't do that, you can make scanf() read a specific number of characters if you want like

float value;
scanf("%4f", &value);

和假设输入

43.23

它会读取

43.2

但你不能指定precision。

but you can't specify precision.

这是没有意义的,你能做的就是

It doesn't make sense, what you can do is

float value;
if (scanf("%f", &value) == 1)
    printf("%.2f\n", value);

毕竟precision由二进制重新presentation有限,因此使得它只有两个小数位是没有意义的,因为在算术运算可能是圆形的。

after all, the precision is limited by the binary representation, so making it have only two decimal places is pointless since in arithmetic operations it might be rounded.

这篇关于如何只接受在scanf中的某个precision(这么多的小数位数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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