k==tail[s].width==k is not the same as tail[s].width == k. You may think you've written something like (k == tail[s].width) && (tails[s].width == k. But C++ doesn't automatically put in && operators like that. What actually happens is that the associativity of the == operator is left to right. So what that actually means is
(k == tails[s].width) == k
Assuming k and tails[s].width are ints, that means (k == tails[s].width) is a bool. The comparison between that and k will be checking if k is 0 or 1, instead of checking if it matches the width as intended.
Another difference is in the placement if your if(eCoada==false) line.
In your working code, it's after the for loop finishes, which means that it only executes once.
In your broken code, it's inside the for loop, which means that every time the loop executes it prints a space. It also means that because you break out of the loop immediately upon setting eCoada to true, you never execute the else branch and never print an o.
C++ 以及我所知道的任何其他语言都不允许在一条语句中进行多次比较。 你不能说 x == y == z, 你必须把他们分开。 if(x ==y && y == z)
C++, nor any other language that I know of, doesn't allow multiple comparisons in one statement. You can't say is x == y == z, you must break them up. if(x ==y && y == z)
发布评论
评论(2)
k==tail[s].width==k
与tail[s].width == k
不同。您可能认为您已经编写了类似(k == tail[s].width) && 的内容。 (tails[s].width == k
。但是 C++ 不会自动放入&&
这样的运算符。实际发生的是==
运算符的关联性 是从左到右。那实际上是什么意思是(k == tails[s].width) == k
假设
k
和tails[s].width
为int< /code>s,这意味着
(k == tails[s].width)
是一个bool
和k
之间的比较。检查k
是否为0
或1
,而不是检查它是否与预期的宽度匹配。的位置。
另一个区别在于您的
if(eCoada==false)
行在您的工作代码中 在for
循环结束后,这意味着它只执行一次,在您损坏的代码中,它位于 for 内部 。 > 循环,这意味着每次循环执行时都会打印一个 空间。这也意味着,由于您在将
eCoada
设置为true
后立即break
跳出循环,因此您永远不会执行else
> 分支并且从不打印o
。k==tail[s].width==k
is not the same astail[s].width == k
. You may think you've written something like(k == tail[s].width) && (tails[s].width == k
. But C++ doesn't automatically put in&&
operators like that. What actually happens is that the associativity of the==
operator is left to right. So what that actually means is(k == tails[s].width) == k
Assuming
k
andtails[s].width
areint
s, that means(k == tails[s].width)
is abool
. The comparison between that andk
will be checking ifk
is0
or1
, instead of checking if it matches the width as intended.Another difference is in the placement if your
if(eCoada==false)
line.In your working code, it's after the
for
loop finishes, which means that it only executes once.In your broken code, it's inside the
for
loop, which means that every time the loop executes it prints a space. It also means that because youbreak
out of the loop immediately upon settingeCoada
totrue
, you never execute theelse
branch and never print ano
.C++ 以及我所知道的任何其他语言都不允许在一条语句中进行多次比较。
你不能说 x == y == z,
你必须把他们分开。
if(x ==y && y == z)
C++, nor any other language that I know of, doesn't allow multiple comparisons in one statement.
You can't say is x == y == z,
you must break them up.
if(x ==y && y == z)