【发布时间】:2014-12-12 06:36:45
【问题描述】:
我正在尝试根据用户想要的数量打印出 Fobonacci 序列。 IE。如果用户输入 5,则输出将为 1,1,2,3,5。所以我在一个普通的 C 程序中设置了一个循环来做到这一点:
for(int m=1; m<=a;m++)
{
i = (pow(c, m)-(pow(v, m)))/b;
printf("%d\n",(int)round(i));
}
这个 for 循环给了我想要的输出。但是,当我将它放入 fork 方法的子进程时,输出会发生变化。 IE。如果用户输入 5,则输出将为 1,0,2,2,5。为什么是这样?有没有办法解决它?这是我的代码:
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <math.h>
int var_glb; /* A global variable*/
int main(void)
{
pid_t childPID;
double a;
double c = 1.6180339;
double v = -0.6190339;
double b = 2.236067977;
int i;
childPID = fork();
if(childPID >= 0) // fork was successful
{
if(childPID == 0) // child process
{
printf("\nEnter the first value:");
scanf("%lf", &a);
for(int m=1; m<=a;m++)
{
i = (pow(c, m)-(pow(v, m)))/b;
printf("%d\n",(int)round(i));
}
}
else //Parent process
{
wait(NULL);
printf("\nThis is the parent process running");
return 0;
}
}
else // fork failed
{
printf("\n Fork failed, quitting!!!!!!\n");
return 1;
}
return 0;
}
【问题讨论】:
-
这不是计算斐波那契数的好方法。事实上,你几乎不应该使用浮点算术来计算可以用纯整数算术表示的东西,无论是正确性还是性能。试试
double fib = (pow(c, m) - pow(v, m)) / b; printf("%f\n", fib);看看发生了什么。
标签: c for-loop fork parent-child fibonacci