即使它不应该使用Printf [英] Printf even though it shouldn't

查看:76
本文介绍了即使它不应该使用Printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有if语句的这一部分,并且得到了一个奇怪的输出.

I have this part of an if statement and I'm getting a weird output.

int x = 10;

if(1 < x < 5){
    printf("F\n");
}

为什么打印"F"?逻辑上说if语句不是假的,因为x大于1但不小于5吗?

Why does it print "F"? Logically isn't the if statement false because x is greater than 1 but not less than 5?

推荐答案

在C语言中,您不能像这样链接比较.表达式 1<x <5 被评估为(1< x)<5 :因此对于 x = 10 ,表达式为(1< 10)<5 .(1< 10)为true,C表示值为 1 ,因此表达式简化为 1<5 .这始终是正确的,并且您的printf()如果已执行.

In C, you can't chain comparisons like that. The expression 1 < x < 5 is evaluated as (1 < x) < 5: so for x = 10, the expression is (1 < 10) < 5. (1 < 10) is true, which C represents as the value 1, so the expression reduces to 1 < 5. This is always true, and your printf() if executed.

正如级别999999所说,在C语言中,您需要显式地将单个比较与&& || 组合.

As level-999999 says, in C you need to explicitly combine single comparisons with && and ||.

这篇关于即使它不应该使用Printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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