从 1 和 2 开始,斐波那契数列的前 10 项将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
求序列中所有不超过 400 万的偶数项之和。
现在,我有了如何做到这一点的想法。但我对保存如此大数据的数据类型感到困惑。我得到了奇怪的结果int。:(
更多:它的 Project Euler 第二个问题。但我无法得到它。我得到了疯狂的价值观作为答案。有人可以发布理想的程序吗?
编辑:这是我写的只是将斐波那契打印到屏幕上。基本款。即使我给出 100 作为限制,我的变量也会变得疯狂。我的代码错了吗?
// Simple Program to print Fibonacci series in Console
#include <stdio.h>
int main() {
    int x=1,y=2,sum=0,limit=0,i=0,temp=0;
    printf("Enter Limit:");
    scanf("%d",&limit);
    if(limit==1)
        printf("%d",x);
    else if(limit>1) {
        printf("%d %d",x,y);
        if (limit>2) {
            while (i<limit-2) {
                temp=y;
                sum=x+y;
                x=temp;
                y=sum;
                printf(" %d",sum);
                i++;
            }
        }
    }      
    printf("\n");
    return 0;
}
已解决:实际上,我自己设法得到了解决方案。这是我的程序。有用。
#include <stdio.h>
int main() {
    int x=1,y=2,sum,limit;     //Here value of first 2 terms have been initialized as 1 and 2
    int evensum=2;             //Since in calculation, we omit 2 which is an even number
    printf("Enter Limit: ");   //Enter limit as 4000000 (4million) to get desired result
    scanf("%d",&limit);
    while( (x+y)<limit ) {
        sum=x+y;
        x=y;
        y=sum;
        if (sum%2==0)
            evensum+=sum;
    }
    printf("%d \n",evensum);
    return 0;
}