To add something to what Mysticial wrote (that is correct): your implementation of C uses float
that are 32 bits IEEE 754 single precision binary floating-point and int
that are 32 bits. In "your" int
you can have 31 bits of number and 1 bit of sign. In "your" float the mantissa
is 24 bits and there is 1 bit of sign. Clearly int
s that need more than 24 bits plus sign to be represented can't be converted exactly to "your" float
. (I use the "your" to represent "your" compiler, the compiler you are using. The C standard doesn't tell the exact length of float
or int
).
Now, the rand()
can generate any int
number, so the compiler has to give you the warning. The 100
is a numeric literal that is known at compile time, so the compiler can statically check if that number is convertible.
(even without explaining exactly how floating points work, your int
is 32 bits and "supports" only integer numbers. Your float
is 32 bits and "supports" floating point numbers. Clearly floating point numbers are more difficult to represent (you have to save somewhere where the decimal point is), so there must be a "price" you pay if both int
and float
have the same length. The price is precision.)
To respond to the comment you made, the maximum number you can represent exactly in a float
that is "contiguous" to 0 (so that 0...number are all exactly representable) are 16777215 (that has mantissa = 16777215 and exponent = 0) and 16777216 (that has mantissa = 1 and exponent = 24, because it's 1 * 2 ^ 24). 16777217 isn't representable exactly. 16777218 is.