Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anomalous behavior of printf()? [duplicate]

Tags:

c

Possible Duplicate:
Using %f to print an integer variable

#include<stdio.h>

int main()
{
    printf("%f",9/5);
    return 0;   
}

Output: 0.000000

Can anyone explain the output of the above program ?

Shouldn't be the output of program be 1.000000 ?

like image 433
dark_shadow Avatar asked Jul 28 '12 17:07

dark_shadow


2 Answers

9/5 is of type int. Passing an int argument to printf with "%f" has undefined behavior.

Try 9.0/5.0 if you want 1.800000, or (double)(9/5) if you want 1.000000

like image 40
Keith Thompson Avatar answered Oct 19 '22 19:10

Keith Thompson


printf("%f",9/5);

This statement is undefined behavior because the argument has to be of type double and 9 / 5 is of type int.

Use 9 / 5.0 to have an argument of type double (and the correct floating division).

like image 190
ouah Avatar answered Oct 19 '22 19:10

ouah