Hi I'm trying to convert from an int
to a float
in C and for some reason the cast changes the value and I'm not sure why. So:
fprintf (stderr, "%d,%d\n", rgbValues->green, (float)rgbValues->green);
produces two different numbers. Note that rgbValues->green开发者_高级运维
is an int
.
Any idea why this is happening?
Thanks
You have to say that in your format string. Use:
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
^
instead of:
fprintf(stderr, "%d,%d\n", rgbValues->green, (float)rgbValues->green);
^
Note the change from d
to f
(the circumflex ^
isn't part of the code, just an indicator as to where to look).
The %d
format specifier says to printf
, "take the next 4 bytes off of the stack, interpret them as an integer, and print out that integer." Since you're actually passing a float
as a parameter, the bytes of the float
(which are stored in IEEE-754 format) are getting misinterpreted as an integer, hence the different values. (Actually, the float
is getting converted to a double
due to argument promotion within variadic functions, and it's the first 4 bytes of that promoted double
that are getting interpreted as an integer.)
The correct solution is to use one of the %e
, %f
, or %g
format specifiers instead of %d
when printing out a float
. %e
says, "take the next 8 bytes off the stack, interpret them as a double
, and print it out using scientific (exponential) notation" %f
prints out using a fixed-point format, and %g
prints out whichever would be shorter of %e
or %f
.
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
Expanding on @AraK's answer, you're casting once to float
, and then printf
is interpreting that bit pattern as an int
in the format specifier string. It's doing exactly what you're telling it to do :)
If you want to only cast to float
- do this:
// format specifier is %d for int, %f for float
// show the cast value of rgbValues->green as well as its "real" value
fprintf(stderr, "%d,%f\n", rgbValues->green, (float)rgbValues->green);
Edit - wording based on comments
精彩评论