+ 2

If we use %d in printf to print a float variable than what it print in c ?

main() { float a=3.8; printf("%d",a); }

10th Feb 2021, 6:57 PM
Ayush Gupta
Ayush Gupta - avatar
8 Antworten
+ 3
It's because the binary representations of the floating point number and it's corresponding integer (when properly cast) are different.
10th Feb 2021, 7:44 PM
Sonic
Sonic - avatar
+ 3
Don't use a format string in printf to cast one type to another unless their internal binary representations are the same.
10th Feb 2021, 8:09 PM
Sonic
Sonic - avatar
+ 1
But it gives 0
10th Feb 2021, 7:11 PM
Ayush Gupta
Ayush Gupta - avatar
+ 1
Strange... It gives 1342327848 without <stdio.h> and -773259752 with <stdio.h> in SoloLearn C Playground... So, the compiler does not convert, it just views data as int and not float.
10th Feb 2021, 7:19 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 1
%d is double precise float therefore won't work because you data type is a float it's recommended to use the%f (float) data type, so it will go like this 👇👇 #include <studio.h> int main() { float a=3.8; printf("%f",a); } Try it
12th Feb 2021, 2:11 PM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
+ 1
get my bad must have been a confusion thanks for clarifying
14th Feb 2021, 7:30 AM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
0
Rick Sanchez (C-137), "%d" format specifier is for integer (<int>). Double-precise float (<double>)'s format specifier is "%lf" (first letter is small L). https://www.sololearn.com/learn/C/2914/ page 3
13th Feb 2021, 6:04 PM
#0009e7 [get]
#0009e7 [get] - avatar