运算符优先级 - 表达式求值

发布于 2024-10-28 00:35:53 字数 144 浏览 1 评论 0 原文

对于以下代码片段,我得到的输出为 1。我想知道它是怎么来的?

void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf("%d",i);
}

For the following code snippet I get the output as 1. I want to know how it came?

void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf("%d",i);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

临风闻羌笛 2024-11-04 00:35:53

i=x,被解释为 i=(x,反过来又被解释为 i=1<; z,其值为 1。

i=x<y<z;, gets interpreted as i=(x<y)<z, which in turn gets interpreted as i=1<z, which evaluates to 1.

傾城如夢未必闌珊 2024-11-04 00:35:53

10 小于 20,结果为 1,1 小于 5,结果为 1。C 不像其他一些语言那样链接关系运算符。

10 is less than 20, resulting in 1, and 1 is less than 5, resulting in 1. C doesn't chain relational operators as some other languages do.

迷爱 2024-11-04 00:35:53

其运作方式如下:
由于<是一个逻辑表达式,所以x10<20为真,即1。所以它变成11<5,这也是正确的,即1 被分配给i。所以i是1。

It operates as follows:
Since < is a logical expression, x<y i.e 10<20 is true i.e 1. So it becomes 1<z i.e 1<5 which is again true i.e. 1 which is assigned to i. So i is 1.

情未る 2024-11-04 00:35:53

这是因为您的代码计算结果为:

void main()
{
    int x=10,y=20,z=5,i;
    i=((x<y)<z); //(x<y) = true = 1, (1 < 5) = true
    printf("%d",i);
}

This is because your code evaluates as:

void main()
{
    int x=10,y=20,z=5,i;
    i=((x<y)<z); //(x<y) = true = 1, (1 < 5) = true
    printf("%d",i);
}
迷迭香的记忆 2024-11-04 00:35:53

你想要什么输出?

在C中,

i = 2 < 3; //i == 1.
i = 4 < 3; //i == 0.

如果条件计算结果为 false,则返回值为 0,否则返回 1。
另外,x<1。 y < z 将被评估为 ((x < y) < z)。

what output did you want?

In C,

i = 2 < 3; //i == 1.
i = 4 < 3; //i == 0.

If condition evaluates to false, value returned is 0, and 1 otherwise.
Also, x < y < z will be evaluated as ((x < y) < z).

雅心素梦 2024-11-04 00:35:53
x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1 
x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1 
怪我闹别瞎闹 2024-11-04 00:35:53

C++ 不支持这样的多部分比较。

x < y < z

被解释为

(x < y) < z

或 即,确定是否 x < y,然后查看该布尔值是否小于 z

关于软件工程 StackExchange为什么有一些讨论。

当您发现自己尝试这样做时,您需要将其编写为由布尔值连接的两个单独的比较:

(x < y) && (y < z)

C++ doesn't support multi-part comparisons like that.

x < y < z

is interpreted as

(x < y) < z

or that is, determine if x < y, then see if that boolean is less than z.

There's some discussion on why that is over at the software engineering StackExchange.

When you find yourself trying to do this, instead you need to write it as two separate comparisons joined by a boolean:

(x < y) && (y < z)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文