C++ 如何一步一步地正确解释此代码?(编程新手)
我的问题是,我不知道编译器如何正确地运行不同的if语句,以及为什么在这种情况下跳过一些if语句 我尝试检查从开始到结束的条件是真是假,从而找到程序的正确输出。但是为什么程序不在这里输出84:C++ 如何一步一步地正确解释此代码?(编程新手),c++,if-statement,syntax,C++,If Statement,Syntax,我的问题是,我不知道编译器如何正确地运行不同的if语句,以及为什么在这种情况下跳过一些if语句 我尝试检查从开始到结束的条件是真是假,从而找到程序的正确输出。但是为什么程序不在这里输出84: if (a > c) cout << 84; else cout << 48 if(a>c)cout a) 如果(a>c)cout这句话毫无意义: if(a
if (a > c) cout << 84;
else cout << 48
if(a>c)cout a)
如果(a>c)cout这句话毫无意义:
if(a
评估结果如下:
if(a
lt/gt/eq/ne/le/ge运算符是二进制运算符,即它们需要两个参数。你应该这样做:
if(a
首先,如果你是新手。不要跳过大括号。现在让我们一步一步地看一遍
在你的第一个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.
}
}
if(ab)>a),当c>b为0时为false,因此它将减少为if(0>c)。执行转到else块。
{
如果(a>c)
{
这难道不是应该的错误吗
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.
}
}