简体   繁体   English

关于输出的困惑

[英]Confusion about the output

#include<stdio.h>
int main(void)
{
    int i=1,j=-1;
    if((printf("%d",i))<(printf("%d",j)))
        printf("%d",i);
    else 
        printf("%d",j);
    return 0;
}

As printf() returns the number of characters successfully printed, the condition will be if(1<1) which is false but the if part is executed and the output is 1 -1 1 . printf()返回成功打印的字符数时,条件将为if(1<1) ,该条件为false,但执行了if部分,输出为1 -1 1 Why this is happening? 为什么会这样呢?

I think it is rather obvious: '1' is one character, '-1' is two. 我认为这很明显:“ 1”是一个字符,“-1”是两个字符。 One is less than two. 一小于二。

printf returns the number of characters (not just digits) written. printf返回写入的字符数(不仅仅是数字)。

So printf("%d",-1) will return 2 not 1 因此printf("%d",-1)将返回2而不是1

Similarly printf("%d",1) will return 1 同样, printf("%d",1)将返回1

Making the condition in the if true. if条件成立, if true。

Because printing j prints "-1", that's two characters. 因为打印j会打印“ -1”,所以这是两个字符。 so 1<2 is true. 所以1 <2是正确的

对于-1 ,如果满足条件,则打印的字符数为2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM