需要帮助解释一小段代码

时间:2017-11-05 03:37:45

标签: c++

所以,我刚接触编码并尝试进入c ++。我试图解决项目欧拉的第二个问题,并认为我已经很好地掌握了如何处理它。几个小时后,我放弃了,决定查阅它。

int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
    x = y;
    y = z;
    z = x + y;
    if (z % 2 == 0)
    {
        sumeven += z;
    }
}
cout << sumeven;

具有

的问题
x=y; y=z; z=x+y;

我理解的一切。

是的,有人可以向我解释一下。我不知道如何在不抬头的情况下知道如何做到这一点。

2 个答案:

答案 0 :(得分:0)

此示例尝试计算偶数Fibonacci序列的总和,Fibonacci序列中的每个数字是添加最后两个数字的结果。所以这就是发生的事情:

  1. 从0开始:int x = 0; \\x is 0 now
  2. 第二个数字是1:int y = 1; \\y is 1 now
  3. 添加它们以获取3d数字:int z = x + y; \\z is 1 now as it's result of adding 0 and 1
  4. y复制到xx = y; \\so x is 1 now, as you can see we are advancing our variables in Fibonacci sequence, It means x is the second number of sequence now
  5. z复制到yy = z; \\as I said, we are advancing in sequence so now y is 3d element of sequence (it was 2nd before) and it's value is 1 now
  6. 根据最后两个元素(zx)计算yz = x + y; \\ so here z would be our 4th element which of course it's calculated by last two so it's value would be 2 as x and y were both 1
  7. 测试是否为偶数:if (z % 2 == 0)
  8. 如果是,请将其添加到我们的求和变量:sumeven += z;
  9. 转到第4步

答案 1 :(得分:0)

始终将

Z设置为前两个数字的总和,其中x为“2个数字前”,y为“前一个数字”。

因此,在计算z之后,必须设置下一次迭代。我们现在希望“2个数字前”成为此次迭代中的y

x = y;

我们希望“之前的数字”为刚刚计算的z

y = z;

现在我们计算新的z:

z = x + y;