我假设我使用了错误的方式,但这个想法是让命令行参数成为我的斐波那契序列的长度...但是我这样做的方式,在 9 之后我就完蛋了...我该如何解决这个问题?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
int fibonacci(int n)
{
int first = 0;
int second = 1;
int total, i;
for (i=0;i<n;i++)
{
printf("%d\n", first);
total = first + second;
first = second;
second = total;
}
return 0;
}
int main(int argc, char *argv[])
{
/*Spawn a child to run the program.*/
pid_t pid=fork();
if (pid==0) { /* child process */
if(*argv[1] == 45){
printf("number invalid \n");
}else{
int number = *argv[1] - 48;
fibonacci(number);
}
}
else { /* pid!=0; parent process */
waitpid(pid,0,0); /* wait for child to exit */
}
return 0;
}
最佳答案
您的方式可以扩展到处理多个数字,但我认为您真正需要的是 atoi()
或未弃用的 strtol()
.
关于C 中的命令行参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594308/