如何一步一步地正确解释此代码?(编程新手)
How do you interpret this code correctly step by step? (New to programming)
我的问题是,我不知道编译器如何正确地运行不同的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.
}
}
}
相关文章:
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 有人能为我解释一下C++代码吗
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 有人可以解释一下这段代码如何能够反转字符串
- 有人可以向我解释一下这段代码的作用吗?
- 有人可以详细解释这个回文代码是如何工作的吗?
- 如何在 C++11 中解释静态代码
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 我不完全确定此代码的行为.有人可以向我解释一下吗?
- 有人可以解释我这个代码吗?它给出与我们输入的数字相反
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 解释以下宏代码的 O/P
- 如何解释 IDA Pro 生成的这些代码?
- 有人能给我解释一下下面的模板代码吗
- 按位 - 代码解释
- 有人可以根据此代码解释起床和降低语法
- 用于人脸检测的Haar级联xml文件代码解释OpenCV
- 代码解释 C++ [结构 / 两个 diamentinal 数组 / 指针]
- int到二进制代码解释C++
- c++代码解释