c++ - Why dοes this code output 1?
问题描述
I'm trying to figure out this C++ code line by line. Can anyone explain it for me? Why is the output 1?
int main() {
int sum = 0;
for (int i=0; i<10; i++)
if (sum%2==0)
sum += i;
else
continue;
cout << sum << endl;
}
解决方案
The code can be roughly translated to the English:
Start with a sum of zero then, for every number from 0 to 9 inclusive, add it to the sum if and only if the current sum is even.
So, you'll add zero to the sum (because the sum is currently even) after which the sum will still be zero (hence even).
Then you'll add one to the sum (because the sum is currently even) after which the sum will be one (hence odd).
Then you'll never add anything to the sum again (because it's odd and will remain so because you're not adding anything to it).
That's why it outputs one.
You may find it more instructive to simply modify your program to output what it's "thinking". The following changes will hopefully make it easier to understand:
#include <iostream>
using namespace std;
int main(void) {
int sum = 0;
for (int i = 0; i < 10; i++) {
cout << "Processing " << i
<< ", sum is " << sum
<< ((sum % 2 == 0) ? " (even):" : " (odd): ");
if (sum % 2 == 0) {
sum += i;
cout << "adding " << i << " to get " << sum;
} else {
cout << "leaving at " << sum;
}
cout << '\n';
}
cout << "Final value is " << sum << '\n';
}
Running that code will show you the steps along the way:
Processing 0, sum is 0 (even): adding 0 to get 0
Processing 1, sum is 0 (even): adding 1 to get 1
Processing 2, sum is 1 (odd): leaving at 1
Processing 3, sum is 1 (odd): leaving at 1
Processing 4, sum is 1 (odd): leaving at 1
Processing 5, sum is 1 (odd): leaving at 1
Processing 6, sum is 1 (odd): leaving at 1
Processing 7, sum is 1 (odd): leaving at 1
Processing 8, sum is 1 (odd): leaving at 1
Processing 9, sum is 1 (odd): leaving at 1
Final value is 1
推荐阅读
- php - $file->move() 函数没有在新文件夹中显示移动的文件?
- c# - NServiceBus 可恢复性失败时发送消息
- javascript - Android WebView WebArchive 加载后冻结
- web-services - SOAP 隐式标头
- ssis - SSIS中依赖限制中的未映射列
- c - 在 for 循环 C 中使用 fscanf 读取文件
- c# - 在错误解析或读取时获取整个 CSV 行
- autodesk-viewer - API 调用强制查看器调整大小以适应约束
- allure - @Step 可以在 Allure 中动态吗?
- html - 滚动条在那里,即使没有内容?