1

This is a very basic question but haven't been able to find a clear explanation. Why does the below code give 30 as a result for k?

I just would like to understand the mechanism, but for some reason, I cannot get my head around this. I know we first start looking at the inner for loop - we get 10 iterations until number2 reaches 10 (and k becomes 10, number 1 becomes 24. But what's next?

int number1(4), number2, k = 0;
        while (number1 < 10) 
        {
            for (number2 = 1; number2 <= 10; number2++)
                ++k;
                number1 = number1 + 2; 
    }
        cout << k << endl;
4

2 回答 2

2

这一行:

number1 = number1 + 2;

不在内部循环中。假设 C/C++,如果您不使用花括号将代码包装在循环内,则只有循环指令之后的第一行被评估为循环代码。

在单个外循环迭代中发生的情况如下:

  1. 内循环运行 10 次。
  2. k增加 10 倍。
  3. 你掉到外循环。number1增加 2。

外循环重复 3 次。因此k增加 3 x 10 倍。

于 2013-05-23T20:19:53.493 回答
1

我在下面的代码中添加了括号。

它与上面的代码相同,但更清晰一些。

int number1(4), number2, k = 0;
    while (number1 < 10) 
    {
        for (number2 = 1; number2 <= 10; number2++)
        {                                             //Added the brackets
            ++k;
        }                        
        number1 = number1 + 2; 
}
    cout << k << endl;

你的缩进很愚蠢

于 2013-05-23T20:27:55.727 回答