首页 > 解决方案 > 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;
}

标签: c++

解决方案


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

推荐阅读