简体   繁体   English

你如何一步一步地正确解释这段代码? (编程新手)

[英]How do you interpret this code correctly step by step? (New to programming)

My problem is that I dont know how the compiler runs through the different if statements correctly and why he skips some in this case.我的问题是我不知道编译器如何正确运行不同的 if 语句以及为什么他在这种情况下跳过了一些语句。

I tried checking if the conditions from start to bottom are true or false and thus find the correct output of the program.我尝试检查从头到尾的条件是真还是假,从而找到程序的正确 output。 But why doesnt the program output 84 here:但是为什么程序 output 84 不在这里:

if (a > c) cout << 84;
else cout << 48

Full Program:完整程序:

int main()
{
  constexpr int a{8};
  constexpr int b{4};
  constexpr int c{1};

  if (a < b < c)
    if (c > b > a)
      if (a > c) cout << 84;
      else cout << 48;
    else
      if (b < c) cout << 14;
      else cout << 41;
  else
    if (b < a < c)
      if (a < c) cout << 81;
      else cout << 18;
    else
      if (b < c) cout << 17;
      else cout << 71;

  return 0;
}

The program outputs only 41. Why?程序只输出 41。为什么?

This statement is a nonsense:这种说法是胡说八道:

if (a < b < c)

It will be evaluated as:它将被评估为:

if (a < bool(b < c))

The lt/gt/eq/ne/le/ge operators are binary - ie they require two arguments. lt/gt/eq/ne/le/ge 运算符是二进制的——即它们需要两个 arguments。 You should be doing something like:您应该执行以下操作:

if (a < b && b < c)

Firstly if you are a newbie.首先,如果您是新手。 Don't skip braces.不要跳过大括号。 Now Let's go through it step by step In your first if-else.现在让我们在你的第一个 if-else 中一步一步地通过它 go。 Here your a=8, b= 4, c=1.这里你的 a=8,b=4,c=1。 This is how your code is proceeding这就是您的代码的执行方式

if (a < b< c)  // equivalent to if(0<c) due to left associativity// firstly a<b will be evaluated which 0 and hence statement  is true as c is 1.
{
if (c > b > a) // equiavelnt to if(bool(c>b)>a) which is false as c>b is 0 hence it will reduce to if(0>c) .execution goes to else block.
{

    if (a > c)
    {
       cout << 84;
    }
    else
    {
       cout << 48;
    }
}
else
{
    if (b < c) // it is false. execution goes to else 
    {
        cout << 14;
    }
    else
    {
        cout << 41; // it is printed.
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM