简体   繁体   English

代码工作正常,但我不明白它显示的内容

[英]Code works fine but I can't understand what it prints

So I'm reading C++ Primer (5th edition) and this is the example code they give to explain the while statement: 因此,我正在阅读C ++ Primer(第5版),这是他们提供的用于解释while语句的示例代码:

#include <iostream>
int main()
{
    int sum = 0, val = 1;
    // keep executing the while as long as val is less than or equal to 10
    while (val <=10) {
        sum += val; // assigns sum + val to sum
        ++val; // add 1 to val
    }
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
    return 0;
}

And this is the program in the Command Line prompt: 这是命令行提示符下的程序:

程序

I just can't understand where the 55 came from.. 我只是不明白55的来源。

Isn't it supposed to be: 它不应该是:

sum = 0
var = 1
sum = 0 + 1
var = 1 + 1
-snip-
sum = 6
var = 4

So shouldn't it print 6? 那它不应该打印6吗? I'm really confused. 我真的很困惑

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

What it does is: 它的作用是:

  1. initializes val to 1 将val初始化为1

  2. increments val till it reaches 10 in each iteration 递增val直到每次迭代达到10

  3. this val is added to sum in each iteration 此val在每次迭代中相加

  4. after 10 iterations, this sums up to 55. 经过10次迭代,总计为55。

Still not clear, use a debugger and check each step. 仍然不清楚,请使用调试器并检查每个步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM