#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个数字是错误的,所以剩余数是错误的。我该如何解决?
谢谢。
最佳答案
我不会回答代码问题,而只是回答问题。
问题是您必须将用来存储两个数字的内存初始化(为零)。在您的代码正常工作之后,我的两个小修改夹在// *注释之间。
#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;
}
关于c - c中的斐波那契数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17914400/