-2
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

/* number of max three digits (max digits = MAX3DIGITS*3) */
#define MAX3DIGITS 100000

/* struct that holds three digits (like 503) */
struct three {
    unsigned n : 10;
};

/* a whole number made up of struct threes */
struct num {
    struct three n[MAX3DIGITS];
} number[2];
FILE *dg;

int main() {


    int naim;
    dg=fopen("deneme.txt","w");



    for(naim=1;naim<1001;naim++){
    int prev = 0;  
    int x, y, n = 0;  
    int digits = 2;  



    number[0].n[0].n = 0;
    number[1].n[0].n = 1;

    while(!kbhit() && ++n < naim && digits <= MAX3DIGITS) {
        //fprintf(stderr, "\r%i", n);

        prev = !prev;

        for(x = 0; x < digits; x ++) {
            y = number[!prev].n[x].n + number[prev].n[x].n;
            number[!prev].n[x].n = (y%1000);
            number[!prev].n[x+1].n += (y/1000);
        }
        if(number[!prev].n[digits-1].n) digits ++;
    }

    fprintf(dg,"\nfib(%i) = %i", n, number[!prev].n[digits-2].n);
    for(x = digits-3; x >= 0; x --) {
        fprintf(dg,"%03i", number[!prev].n[x].n);
    }
    fprintf(dg,"\n");


    }
    printf("sad");
    if(kbhit()) getche();
    getchar();
    getchar();
    return 0;
}

此代码正在编写前 1000 个斐波那契数。但我的问题是从第 18 个数字开始。直到第十七号,此代码才有效。但是第 18 个数字是错误的,所以剩下的数字是错误的。我该如何解决?

谢谢你。

4

1 回答 1

4

我不会对代码提出考虑,而是回答这个问题。问题是您必须将用于存储两个数字的内存初始化(为零)。在您的代码的工作版本之后,我的两个小修改夹在 // *注释之间。

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
// *****
#include <mem.h>
// *****

/* number of max three digits (max digits = MAX3DIGITS*3) */
#define MAX3DIGITS 100000


/* struct that holds three digits (like 503) */
struct three {
    unsigned n : 10;
};

/* a whole number made up of struct threes */
struct num {
    struct three n[MAX3DIGITS];
} number[2];
FILE *dg;

int main() {


    int naim;
    dg=fopen("deneme.txt","w");


    for(naim=1;naim<1001;naim++){
    int prev = 0;
    int x, y, n = 0;
    int digits = 2;

    // *****
    memset(number, 0, sizeof(number));
    // *****

    number[0].n[0].n = 0;
    number[1].n[0].n = 1;

    while(!kbhit() && ++n < naim && digits <= MAX3DIGITS) {
        //fprintf(stderr, "\r%i", n);

        prev = !prev;

        for(x = 0; x < digits; x ++) {
            y = number[!prev].n[x].n + number[prev].n[x].n;
            number[!prev].n[x].n = (y%1000);
            number[!prev].n[x+1].n += (y/1000);
        }
        if(number[!prev].n[digits-1].n) digits ++;
    }

    fprintf(dg,"\nfib(%i) = %i", n, number[!prev].n[digits-2].n);
    for(x = digits-3; x >= 0; x --) {
        fprintf(dg,"%03i", number[!prev].n[x].n);
    }
    fprintf(dg,"\n");


    }
    printf("sad");
    if(kbhit()) getche();
    getchar();
    getchar();
    return 0;
}
于 2013-07-29T01:16:34.723 回答