#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个数字是错误的,所以剩下的是错的。我该如何解决?
谢谢。
答案 0 :(得分: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;
}