我想打印出Fobonacci序列根據用戶想要多少個數字。即如果用戶輸入5,則輸出將是1,1,2,3,5。所以我在一個普通的C程序中設置一個循環來執行此操作:奇怪的結果使用內循環兒童方法在C
for(int m=1; m<=a;m++)
{
i = (pow(c, m)-(pow(v, m)))/b;
printf("%d\n",(int)round(i));
}
這個for循環給了我期望的輸出。但是,當我將它放入fork方法的子進程中時,輸出會發生變化。即如果用戶輸入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);'看看發生了什麼。 – 5gon12eder 2014-10-16 19:35:11