简体   繁体   English

为什么printf(“%。1f”,1)输出0.0

[英]Why printf(“%.1f”, 1) output 0.0

I use the codeblock . 我使用代码块

when the code is: 当代码是:

printf("%.1f", 1);

The program can run,and the output is 0.0 . 程序可以运行,输出为0.0 I want to know why. 我想知道为什么。 ` `

Change it to: 更改为:

printf("%.1f", 1.0);

f conversion specifier requires an argument of type double but you are passing an int value ( 1 is of type int ). f转换说明符需要一个double类型的参数,但是您要传递一个int值( 1int类型)。 Passing an argument of the wrong type to printf invokes undefined behavior. 将错误类型的参数传递给printf调用未定义的行为。

Using wrong format specifier invokes undefined behavior . 使用错误的格式说明符会导致未定义的行为 You may get either expected or unexpected result. 您可能会得到预期的结果或意外的结果。 Use %d instead as the argument passed to printf is int type or change 1 to 1.0 if you are using %f . 使用%d代替,因为传递给printf的参数是int类型,或者如果使用%f则将1更改为1.0

C11: 7.21.6 (p9): C11:7.21.6(p9):

If a conversion specification is invalid, the behavior is undefined. 如果转换规范无效,则行为未定义。 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. 282)如果任何参数不是对应转换规范的正确类型,则行为未定义。

The format is incorrect , you should give a float or a double as the second argument to the printf function. 格式不正确,您应该给floatf或double作为printf函数的第二个参数。 The gcc compiler also gives a warning on such mistakes by programmers. gcc编译器还会针对程序员的此类错误给出警告。

 printf("%.1f",1.23);

Output: 输出:

 1.2

Be carefull with these kind of mistakes. 请谨慎对待此类错误。 Good luck! 祝好运!

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

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