2016-06-11 62 views
-1

預先感謝您。我很欣賞任何和所有的反饋。我是編程新手,我正在開發一項基於用戶請求的數字打印斐波納契數列的任務。我已經完成了大部分代碼,但還有一件我很困難。我希望以表格格式輸出,但是我的代碼有些問題,並且我沒有在輸出中獲得所有我想要的數據。灰色是我的代碼,我的輸出和我想要的輸出。爲斐波那契序列創建表格

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
int i, n; 
int sequence = 1; 
int a = 0, b = 1, c = 0; 

printf("How many Fibonacci numbers would you like to print?: "); 
scanf("%d",&n); 

printf("\n n\t\t Fibonacci Numbers\n"); 

printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b); 

for (i=0; i <= (n - 3); i++) 
{ 
    c = a + b; 
    a = b; 
    b = c; 
    sequence++; 
    printf("\t\t\t%d\n ", c); 
} 
return 0; 
} 

Here is my output: 
How many Fibonacci numbers would you like to print?: 8 

n  Fibonacci Numbers 
1   0 
      1 
      1 
      2 
      3 
      5 
      8 
      13 

Here is my desired output: 
How many Fibonacci numbers would you like to print?: 8 

n  Fibonacci Numbers 
1   0 
2   1 
3   1 
4   2 
5   3 
6   5 
7   8 
8   13 
+0

您是不是要找'的printf(「%d \ t \ t \ t%d \ n「,序列,c);'? – user3078414

回答

0

我沒有得到所有的數據

  • 那是因爲你沒有在for循環printf()打印sequence的。

    printf("\t\t\t%d\n ", c); 
    
  • ,甚至前2 第二號碼前for循環

    printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b); 
    

嘗試使下面的代碼修改:

​​

樣本輸入:5

輸出樣本:

How many Fibonacci numbers would you like to print?: 5 
n  Fibonacci Numbers 
1   0 
2   1 
3   1 
4   2 
5   3 

編輯:你可以使用函數這樣做......這幾乎是同樣的事情: )

#include <stdio.h> 

void fib(int n) 
{ 
    int i,sequence=0,a=0,b=1,c=0; 

    printf("\n n\t\t Fibonacci Numbers\n"); 

    printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b); 

    sequence++; 

    for (i=0; i <= (n - 2); i++) 
    { 
     c = a + b; 
     a = b; 
     b = c; 
     printf("%d\t\t\t%d\n ",++sequence, c); 
    } 
} 

int main() 
{ 
int n; 

printf("How many Fibonacci numbers would you like to print?: "); 
scanf("%d",&n); 
fib(n); 

return 0; 
} 
+0

@ lopezgera92很高興你明白了:)...接下來,當你有輸出問題時,仔細觀察每一個'printf()'sindment – Cherubim

+0

如果你不介意,我還有一個問題。該任務要求我「包含一個函數fib(),該函數從main()中接收輸入參數,告訴該函數要輸出多少個斐波那契數字」。我對如何將我的輸入「n」從main()傳遞給fib()有點困惑。我會怎麼做呢? @CherubimAnand – lopezgera92

+0

當然我會在幾分鐘內更新@ lopezgera92 – Cherubim

0

您忘記了在for循環中打印sequence。打印sequence以及c for循環後給予適當數量的\t

+0

感謝您的快速回復@DeeJay – lopezgera92

0

這會工作,也最好是正確indentate代碼:

int main() { 
    int i, n; 
    int sequence = 1; 
    int a = 0, b = 1, c = 0; 

    printf("How many Fibonacci numbers would you like to print?: "); 
    scanf("%d",&n); 

    printf("\n n\t\tFibonacci Numbers\n"); 

    printf(" %d\t\t\t%d\n", sequence, a); 
    printf(" %d\t\t\t%d\n", ++sequence, b); // <- and you can use pre increment operator like this for your purpose 

    for (i=0; i <= (n - 3); i++) { 
     c = a + b; 
     a = b; 
     b = c; 
     sequence++; 
     printf(" %d\t\t\t%d\n",sequence, c); 
    } 

    return 0; 
} 

輸出:

How many Fibonacci numbers would you like to print?: 4 

n  Fibonacci Numbers 
1   0 
2   1 
3   1 
4   2