所以,我刚接触编码并尝试进入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;
我理解的一切。
是的,有人可以向我解释一下。我不知道如何在不抬头的情况下知道如何做到这一点。答案 0 :(得分:0)
此示例尝试计算偶数Fibonacci序列的总和,Fibonacci序列中的每个数字是添加最后两个数字的结果。所以这就是发生的事情:
int x = 0; \\x is 0 now
int y = 1; \\y is 1 now
int z = x + y; \\z is 1 now as it's result of adding 0 and 1
y
复制到x
:x = 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
z
复制到y
:y = 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
z
和x
)计算y
:z = 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
if (z % 2 == 0)
sumeven += z;
答案 1 :(得分:0)
Z
设置为前两个数字的总和,其中x
为“2个数字前”,y
为“前一个数字”。
因此,在计算z
之后,必须设置下一次迭代。我们现在希望“2个数字前”成为此次迭代中的y
:
x = y;
我们希望“之前的数字”为刚刚计算的z
:
y = z;
现在我们计算新的z:
z = x + y;