printf输出错误 [英] printf giving wrong output

查看:153
本文介绍了printf输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

给出的输出: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));
    }

给出的输出:8.000000 0.000000

Gives Output : 8.000000 0.000000

为什么这样???请解释

Why like that??? please explain

推荐答案

问题不仅与格式说明符有关,而且还与您定义宏的方式有关.应该是:

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))

宏也不是安全类型.现在,如果您对结果进行转换,您将看到正在发生的事情,因为4的平方是16,而8/16的平方是0.5,被截断为int,因此变为0.对于正确的值,这是您应该键入的方式:

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)));

示例输出:

0 0
0.000000 0.500000

这篇关于printf输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆