简体   繁体   English

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

[英]Maximum field width of scanf() with float

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() function 的控制字符串中指定的最大字段宽度指定可以读入变量的最大字符数。

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.根据这个解释,如果以下代码的输入是123.456 ,则 output 应该是123.45 ,但我得到123.4作为 output。

#include <stdio.h>

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

    return 0;
}

I am unable to understand the reason for the output.我无法理解 output 的原因。

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.如果以下代码的输入是 123.456,则 output 应该是 123.45,但我得到 123.4 作为 output。

Yes, you are getting the right output as per the code you have written.是的,根据您编写的代码,您得到了正确的 output。

The "%5f" you used in scanf , specifies the maximum number of characters to be read in the current reading operation.您在scanf中使用的"%5f"指定了当前读取操作中要读取的最大字符数。

so in your output, 123.4 are 5 characters( including the . )所以在你的 output 中, 123.4是 5 个字符(包括.

If you want to print x number of digits after .如果x. , use %.xf , 使用%.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;
}

output: output:

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() function 的控制字符串中指定的最大字段宽度指定可以读入变量的最大字符数。

Not quite.不完全的。

With scanf("%5f", &f);使用scanf("%5f", &f); , the "%5f" directs scanf() to first read and discard leading white-spaces. , "%5f"指示scanf()首先读取并丢弃前导空格。 These white-spaces do not count toward the 5.这些空格不计入 5。

Then up to 5 numeric characters are read.然后最多读取 5 个数字字符。 These include 0-9, - +, e, E, NAN, nan, inf...其中包括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

Using a width limit with "%f" in scanf() can be problematic.scanf()中使用带有"%f"的宽度限制可能会出现问题。 Consider setting aside scanf() and use fgets() to read user input into a string and then parse the string.考虑搁置scanf()并使用fgets()将用户输入读入字符串,然后解析字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM