Why you mustn't write scanf(“%.2lf”, &a) in C?

后端 未结 2 713
萌比男神i
萌比男神i 2021-01-27 02:57

My friend have just started learning programming. He showed me his code and asked why it return some weird number. After taking a look at it, I saw that he was using sca

2条回答
  •  梦谈多话
    2021-01-27 03:55

    The C standard specifies that scanf conversion specifiers begin with %, and the POSIX standard specifies they begin with either % or %n$.

    Neither the C standard nor the POSIX standard allows for a . in the conversion specifier, so this character is invalid.

    You may have a decimal integer in your conversion specifier before the type specifier, but it specifies the maximum field width of the type. This means that scanf will read at most 2 characters before stopping when passed %2lf.

    Additionally, lf specifies that the value should be a double, so a should be of type double.

提交回复
热议问题