2014-10-16 107 views
0

我想打印出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; 
} 
+0

這不是計算斐波那契數的好方法。實際上,你幾乎不應該使用浮點運算來計算可以用純整數算術表達的東西,以保證正確性和性能。試試'double fib =(pow(c,m) - pow(v,m))/ b; printf(「%f \ n」,fib);'看看發生了什麼。 – 5gon12eder 2014-10-16 19:35:11

回答

1

我會通過固定支架的開始:i = (pow(c, m)-pow(v, m))/b;你也不能指望iint ... ifloatdouble

+0

而這就是問題:當該表達式被分配給變量'i'時,結果被截斷爲整數。它需要被舍入。 – 2014-10-16 19:29:03

0

你的問題是不相關的分叉。如果所有的分支都被註釋掉了,那麼程序產生完全相同的結果,並且所有的東西都在父進程中運行。顯然,該算法在某些方面是不正確的。

0

因此我發現問題在於我將變量i聲明爲int而不是double,就像我在另一個應用程序中所做的一樣,感謝您的幫助,但我一定會使用所有的建議來加強我的碼。