+ 2

A question from new learner of C

Hi, I just started learning C, I have a question. The correct answer had been changed after I purposely changed the order between an integer and the float. May I know how is the number (-1210612736) calculated? What is the logic behind this? https://code.sololearn.com/c95788T34e7u/?ref=app Thank you very much!

3rd Jan 2018, 3:52 PM
weilun29s
8 Respostas
+ 8
this large number is garbage value which is randomly set by ram.. when a variable doesn't match to his format specifier then compile search for a memory location and randomly selected memory location set to this variable value and then print a big chunk of value
3rd Jan 2018, 4:29 PM
Scooby
Scooby - avatar
+ 8
welcome.. keep learning .. stay connected to sl ☺
3rd Jan 2018, 4:33 PM
Scooby
Scooby - avatar
+ 6
quotient = i1 / i2; // 3(wrong answer because in printf u put %f format specifier although it should be %d) remainder = i1 % i2; // 1 result = f1 / f2; // 1.68 i(put %f in printf) printf ("%d,%d, %f", remainder, result, quotient); return 0;
3rd Jan 2018, 4:15 PM
Scooby
Scooby - avatar
+ 6
right code #include <stdio.h> int main() { int i1 = 10; int i2 = 3; int quotient, remainder; float f1 = 4.2; float f2 = 2.5; float result; quotient = i1 / i2; // 3 remainder = i1 % i2; // 1 result = f1 / f2; // 1.68 printf ("%d,%f, %d", remainder, result, quotient); return 0; }
3rd Jan 2018, 4:18 PM
Scooby
Scooby - avatar
+ 6
It is not that at all. In fact, printf analyze result as an integer and read its binary representation as so, but the binary representation of an integer is really different from a floating point number so the junk value is just a bad interpretation of your number (proof is, you always get the same number)
3rd Jan 2018, 7:20 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 4
You used float as result type so use %f to print it
3rd Jan 2018, 4:19 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Thank you both for the answers! I know the specifier is wrong, I purposely put it like this to see what happen. I thought the value of float would be 1 or 0 or invalid value, but it turned out to be a huge number (-1210612736), I would like to know how does the compiler get this number, and the logic behind this. Thanks again!
3rd Jan 2018, 4:28 PM
weilun29s
+ 1
Great thanks! Now I finally got it, really appreciate your help 😁 Have a nice day~
3rd Jan 2018, 4:32 PM
weilun29s