问题
I have to program a little program that show a Fibonacci sequence from 1 to n. 1 to 18 works great. But from 19 the program does nothing at all and just exit as it's done. I can not find the error... so please give me an hint.
#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
pid_t pid;
int fib[argc];
int i, size;
size = strtol(argv[1], NULL, 0L);
fib[0] = 0;
fib[1] = 1;
pid = fork();
printf("size = %d \n", size);
if(pid == 0){
for(i = 2; i < size; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(i = 0; i < size; i++){
printf("\n\t %d ", fib[i]);
}
}
else if(pid > 0){ // Parent, because pid > 0
wait(NULL);
printf("\n");
exit(1);
}
}
回答1:
Some issues are:
.fib[0]
should be1
, not0
- Size of
fib
array is wrong. - And array
fib
is defined wrong too. - Seems that
for
fill random membery, notfib
array elements.
回答2:
Still this code doesn't look very good. You haven't posted includes and for-loop is incomplete. It doesn't even contain code that will actually compute the sequence values.
Next problem is the purpose of forking here. What you want to do is to perform simple sequential calculation. There is no need for fork at all.
I recommend a bit more work on this before submitting this for grade.
来源:https://stackoverflow.com/questions/2880306/fibonacci-in-c-works-great-with-1-18-but-19-does-nothing-at-all