OR gives invalid results

1 次查看(过去 30 天)
HARI
HARI 2022-3-21
编辑: Stephen23 2022-3-21
Hello,
Please see the attached picture.
Its very simple but i dont get the correct results.Can anyone clarify why it outputs 12 instead of 22?
  1 个评论
Stephen23
Stephen23 2022-3-21
编辑:Stephen23 2022-3-21
"OR gives invalid results"
Actually OR gives exactly the expected result.
"Can anyone clarify why it outputs 12 instead of 22?"
Following the rules of precedence given here:
we can see that EQ has a higher precedence than short-circuiting ||, so your code
left == 1 || 3
is equivalent to:
(left == 1) || 3
which will always be TRUE because 3 is non-zero and so is considered TRUE.
"Its very simple but i dont get the correct results"
Yet MATLAB is just doing exactly what you told it to do. You need to pay attention to the operator precedence!

请先登录,再进行评论。

采纳的回答

Torsten
Torsten 2022-3-21
if left == 1 || left == 3
...
The condition "3" is empty and thus true. MATLAB does not relate the "3" to "left".

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by