简体   繁体   中英

Why does printf(“value: %f”,10/2); output 0.000000?

我知道整数算术将截断分数,但在这里它至少应打印5。为什么打印0.000000

The call of printf has undefined behavior because the conversion specifier %f does not correspond to the type of the expression 10 / 2 , which is int . As the two operands of the expression 10 / 2 have the type int , the result has the type int because it is the common type of the both operands.

Use instead at least 10.0 / 2 . In this case, the expression has the type double .

Or output the integer expression 10 /2 using conversion specifier %d or %i like

printf( "value: %d", 10 / 2 );

From the C Standard (7.21.6.1 The fprintf function)

9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined .

10 and 2 aren't valid float s. They are int s.

To have your program print correct output, do this:

printf("value:%f",10./2.);

Notice the . after each number. This signifies to the compiler that the number is a floating-point number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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