How to only accept a certain precision (so many decimals places) in scanf?

后端 未结 4 1375
刺人心
刺人心 2020-12-04 01:33

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\",

4条回答
  •  没有蜡笔的小新
    2020-12-04 02:17

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

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

    and suppose the input is

    43.23
    

    it will read

    43.2
    

    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);
    

    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.

提交回复
热议问题