提问者:小点点

C++中的IF嵌套


嘿,我只是在浏览我的C++入门课程的一些教科书示例,如果有人能解释一下为什么下面的代码会产生51的输出(我希望它不会产生任何输出),我会非常感激的,非常感谢!:

#include <iostream>
using namespace std;

int main()
{
  constexpr int a{9};
  constexpr int b{1};
  constexpr int c{5};

  if (a < b < c)
    if (c > b > a)
      if (a > c) cout << 91;
      else cout << 19;
    else
      if (b < c) cout << 51;
      else cout << 15;
  else 
    if (b < a < c)
      if (a < c) cout << 95;
      else cout << 59;
    else
      if (b < c) cout << 57;
      else cout << 75;

  return 0;
}

共2个答案

匿名用户

看来你期待这样的表达:

if (a < b < c)

如果abc按递增顺序排列,则为true。 但实际发生的情况是,这个表达式变成了:

if ((a < b) < c)

即:

if (0 < c)
// or
if (1 < c)

不管怎样,那可能不是你想要的。 事实上,没有好的理由编写上面的表达式。

如果要检查变量是否在增加,需要编写如下内容:

if (a < b && b < c)

匿名用户

在C++中,像'x<=y<=z'这样的比较在没有括号的情况下没有数学意义。 所以,在

if (a < b < c)

我们得到了

a < b => 9 < 1 => 0

“0”表示条件为false,该条件与“c”一起返回

0 < 5 => 1

返回“1”表示if条件为真。

类似地,您可以检查嵌套的if-else循环。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|嵌套)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?