+ 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!
8 Respuestas
+ 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
+ 8
welcome.. keep learning .. stay connected to sl ☺
+ 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;
+ 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;
}
+ 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)
+ 4
You used float as result type so use %f to print it
+ 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!
+ 1
Great thanks! Now I finally got it, really appreciate your help 😁
Have a nice day~