What happens when I pass an integer to a float variable ? Can someone explain me the output of this code ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What happens when I pass an integer to a float variable ? Can someone explain me the output of this code ?

The code : #include <stdio.h> int main() { int a; float b; int c; scanf("%d", &a); scanf("%d", &b); scanf("%d", &c); printf("%d\n", a); printf("%d\n", b); printf("%d", c); return 0; } The Input : 8.33334 124 The Output : 8 4195929 32765

25th Aug 2021, 6:28 AM
Sk. Ahmed Razha Khan
Sk. Ahmed Razha Khan - avatar
2 Answers
+ 2
Ahmed, Try with initialised values, int a = 0; float b = 0.0; int c = 0; It reads only value of variable 'a' our any error. It reads 'a' as 8 for given input. 'b' and 'c' remains as it is. Incase it is not initialised then garbage value shown in output. 'a' is read as 8 since int value does not have any decimal point. 'b' and 'c' does not read any value because following scanf() is also tries to read int. So initial value get printed. DHANANJAY
25th Aug 2021, 7:05 AM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
0
The first thing that caught my eyes on that code is, the use of inappropriate conversion specifier %d used for reading input for a `float` variable <b>. I guess it's enough to tell that we can't get an expected output given that the input was read in using an inappropriate conversion specifier. https://stackoverflow.com/questions/12830052/wrong-format-specifiers-in-scanf-or-printf
25th Aug 2021, 9:19 AM
Ipang