我已经尝试用 C 语言解决 Project Euler 中的问题 2。这是我想到的第一个可能的解决方案,事实上,它给出了正确答案的输出。问题是每次我运行我的程序时,它都会给我一个不同的输出,正确答案是“2”或“4613732”。抱歉我的英语不好,你能帮我找出问题所在吗?
#include <stdio.h>
int main(){
int n, n1 = 1, n2 = 2, sum = 2;
while(n<4000000){
n = n1 + n2; /*calculate the next number of the series*/
n1 = n2;
n2 = n;
if(n%2 == 0){
sum = sum + n; /*if the number it's even add it to the main sum*/
}
}
printf("The sum is %d\n", sum);
}
最佳答案
你没有初始化n
;当你得到正确答案时,就意味着你很幸运。
关于c - 欧拉计划 2# - 奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40052909/