开发者

C printf using %d and %f

开发者 https://www.devze.com 2022-12-20 03:14 出处:网络
I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens?

I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens?

int main ()
{
 float a = 1F;
 double b = 1;

 printf("float =%d\n开发者_JAVA技巧double= %f", a, b);
}

This is the output

float = -1610612736
double = 190359837192766135921612671364749893774625551025007120912096639276776057269784974988808792093423962875123204096.0000


%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double) and both of them use %f. In C99 you can also use %lf to signify the larger size of double, but this is purely cosmetic (notice that with scanf no promotion occurs and this actually makes a difference).


Because of the way variable parameters work, C has no idea of the type of value you are actually passing it other than %d and %f. When you pass in a variable parameter you are basically doing (void*)&myvalue because neither the compiler, nor the function at run time can determine the type of the variable except for what is given in the formatting string. So even though there is an implicit conversion available, the compiler does not know it is needed.

Well, double is 8 bytes on most systems while float is 4 bytes. So the two types are not binary compatible as it is. And it is like trying to interpret a string as a double, or some other incompatible type.


It has to do with internal representations of data. You are trying to print a float as if it is an int, which has a completely different internal (binary) representation.

The double case is similar. You probably have garbage (any data) after the float variable. That garbage is interpreted as part of the double value.


%d prints an integer, so your printf is interpreting your variable a as an int.

With gcc 3.4.6, I get 0's for both values with your code (after taking the F off the a initialization, as that led to a compiler error). I suspect this has to do with the part of the a variable that is being interpreted as an int being 0, and then the compiler gets confused ... (there's probably a better explanation, but I can't think of it).

Using %f for both variable prints 1.000000 for both variables for me.

You can find a list of the conversion characters near the bottom this page:

http://www.exforsys.com/tutorials/c-language/managing-input-and-output-operations-in-c.html

0

精彩评论

暂无评论...
验证码 换一张
取 消