printf giving wrong output [closed]

2019-10-20 17:51发布

问题:

#include<stdio.h>
#define square(x) x*x

    void main()
    {
        int i;
        i = 8 / square(4);
        printf("%d %d", i, 8/square(4));
    }

Gives output : 8 8

but if I write below code :

#include<stdio.h>
#define square(x) x*x

    void main()
    {
        float i;
        i = 8 / square(4);
        printf("%f %f", i, 8/square(4));
    }

Gives Output : 8.000000 0.000000

Why like that??? please explain

回答1:

The problems are not just with the format specifier but also the way you have defined your macro. It should be:

#define square(x) ((x)*(x))

Also macros are not type safe. Now if you cast your results you will see what is happening, since the square of 4 is 16 and 8/16 is 0.5 which gets truncated to int hence becomes 0. For proper values this is how you should typecast:

printf("%d %d", (int)i, (int)(8/square(4)));
printf("\n%f %f", (float)i, (float)8/((float)square(4)));

Sample Output:

0 0
0.000000 0.500000


回答2:

First of all correct this:

#define square(x) x*x

to

#define square(x) ((x)*(x))

for correct results after macro replacement.

Now, in your first program, as others explained you are using wrong format specifier %f to print an integer (8/(square(4) will evaluate to an integer), which is undefined behavior.

In second program, 8/square(4) is type promoted to float as you are storing the result in float i. Therefore, you get 8.000000 on first printing. On second printing, result is wrong due to same reason as above.



回答3:

The first is easy to understand so I focus on the second only. You use %f for the second parameter which requires a float number while C compiler take 8/square(4) as integer. This mismatch corrupt your result.



回答4:

8/square(4) results to an int and trying to print an integer using %f is Undefined behavior. So there is no use of debugging the value you got in second case.

If you are using gcc compiler then command cc -E filename.c may clarify your doubts.



回答5:

It is because you given float as datatype in second program.

8/square(4) will give an integer result, and hence your output becomes wrong. you used %f to print an integer.

That is so simple...



回答6:

because %f means the type of number is double and default precision



标签: c macros printf