【问题标题】:Maximum field width of scanf() with float带浮点数的 scanf() 的最大字段宽度
【发布时间】:2021-01-03 10:37:39
【问题描述】:

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

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

#include <stdio.h>

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

    return 0;
}

我无法理解输出的原因。

【问题讨论】:

  • 123.4 不是五个字符吗?你没有得到123.400002 作为输出吗?
  • Sindhuja,“但我得到 123.4 作为输出”--> 最好发布准确的真实输出,它更像 "123.400001" 而不是 "123.4"

标签: c floating-point scanf


【解决方案1】:

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

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

您在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

【讨论】:

    【解决方案2】:

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

    不完全是。

    使用scanf("%5f", &amp;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() 将用户输入读入一个字符串,然后解析该字符串。

    【讨论】:

    • 哦,我对 C 语言有点陌生,所以我还在寻找最好的输入法。我会确保查看fgets()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 2012-05-31
    • 2014-09-04
    • 1970-01-01
    • 2012-08-20
    • 2021-10-23
    • 2011-10-23
    相关资源
    最近更新 更多