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



我的问题是,我不知道编译器如何正确地运行不同的if语句,也不知道他为什么在这种情况下跳过一些语句。

我试着检查从开始到底的条件是真是假,从而找到程序的正确输出。但是为什么程序不在这里输出84:

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

完整程序:

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;
}

该程序仅输出41。为什么?

这句话纯属无稽之谈:

if (a < b < c)

它将被评估为:

if (a < bool(b < c))

lt/gt/eq/ne/le/ge运算符是二进制的,即它们需要两个参数。你应该做这样的事情:

if (a < b && b < c)

如果你是新手,首先。不要跳过牙套。现在让我们一步一步来在你的第一个if else。这里你的a=8,b=4,c=1。这就是你的代码进行的方式

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.
}
}

}

最新更新