<分区>
Possible Duplicate:
Sum of even fibonacci numbers
目前,我正在做一些欧拉计划问题,我正在解决第二个问题。
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
我正在用 C++ 解决这个问题,我认为我的代码非常好,因为在某种程度上,一切都是正确的,但随后,一切都失控了...... 代码:
#include <iostream>
using namespace::std;
int main() {
int a = 1;
int b = 1;
int evsum = 0;
while (a < 4000000 and b < 4000000) {
a = a + b;
b = a + b;
if (a % 2 == 0)
evsum += evsum + a;
if (b % 2 == 0)
evsum = evsum + b;
cout << a << endl;
cout << b << endl;
cout << evsum << "evensum" << endl;
}
}
xCode 编译器正确打印所有内容,直到...
2
3
2evensum
5
8
10evensum
13
21
10evensum
...
...
233
377
198evensum
610
987
1006evensum
由于某些原因,编译器将 610 添加到 198 并认为它等于 1006!我该如何解决这个问题???