带浮点数的 scanf() 的最大字段宽度

Maximum field width of scanf() with float

scanf()函数中的控制字符串中指定的最大字段宽度指定了可以读入变量的最大字符数。

根据这个解释,如果以下代码的输入是 123.456,输出应该是 123.45,但我得到的是 123.4 作为输出。

#include <stdio.h>

int main() {
    float f;
    scanf("%5f", &f);
    printf("%f", f);

    return 0;
}

我无法理解输出的原因。

According to this explanation,
if the input for the following code is 123.456, the output should be 123.45 but I am getting 123.4 as the output.

是的,根据您编写的代码,您得到了正确的输出。

你在scanf中使用的"%5f",指定了当前读取操作要读取的最大字符数。

所以在你的输出中,123.4 是 5 个字符(包括 .

如果要在 . 之后打印 x 位数,请使用 %.xf

#include <stdio.h>
    
int main() {
    float f;
    printf("Enter a float number:");
    scanf("%f", &f);
    printf(" with .2f = %.2f\n", f);
    printf(" default  = %f\n", f);
    
    return 0;
}

输出:

Enter a float number:123.456
 with .2f = 123.46
 default  = 123.456001

The maximum field width specified in the control string in the scanf() function specifies the maximum number of characters that can be read into the variable.

不完全是。

对于 scanf("%5f", &f);"%5f" 指示 scanf() 首先读取并丢弃前导空格。这些空格不计入 5。

然后最多读取 5 个数字字符。其中包括 0-9, - +, e, E, NAN, nan, inf...

  12345
 "123.45"     --> "123.4" is read, "5" remains in stdin
 "-123.45"    --> "-123." is read, "45" remains in stdin
 "+123.45"    --> "+123." is read, "45" remains in stdin
 "000123.45"  --> "00012" is read, "3.45" remains in stdin
 "1.2e34"     --> "1.2e3" is read, "4" remains in stdin
 "123x45"     --> "123" is read, "x45" remains in stdin
 " 123.45"    --> " 123.4" is read, "5" remains in stdin

scanf() 中使用 "%f" 的宽度限制可能会出现问题。考虑搁置 scanf() 并使用 fgets() 将用户输入读取到 字符串 中,然后解析该字符串。