2016-11-13 85 views
0
#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    system("color f0"); 
    int k,i,j,n; 

    printf("Generate tables upto:"); 
    scanf("%d",&n); 
    int tables[n][10]; 
    printf("Table\t"); 
    for(k=1;k<=10;k++) 
    { 
     printf("%dx\t",k); 
    } 
    printf("\n"); 
    for(i=1;i<=n;i++) 
    { 
     for(j=1;j<=10;j++) 
     { 
      tables[i][j]=i*j; 
      printf("%d\t",tables[i][j]); 
     } 
    } 
    return 0; 
} 

這個是我的代碼我的工作,但不幸的是我不能夠生成它,我想要的方式。 所需的輸出應該看起來像this如何使用數組生成表?

+4

C數組開始你知道0。 –

+0

另外,如果你得到一個SegFault(你可以運行這段代碼)嘗試使用'gdb'或'valgrind'來找出原因。 –

+0

...與'表[i] [j] = i * j;'是*未定義行爲*。 –

回答

1

建議修復您的代碼

  • C-數組從0開始
  • 你錯過了在適當的標籤和換行地點

代碼:

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

int main() 
{ 
    system("color f0"); 
    int k,i,j,n; 

    printf("Generate tables upto:"); 
    scanf("%d",&n); 
    int tables[n][10]; 
    printf("Table\t"); 
    for(k=1;k<=10;k++) 
    { 
     printf("%dx\t",k); 
    } 
    printf("\n"); 
    for(i=2;i<=n;i++) 
    { 
     printf("%d\t",i); 
     for(j=1;j<=10;j++) 
     { 
      tables[i-1][j-1]=i*j; 
      printf("%d\t",tables[i-1][j-1]); 
     } 
     printf("\n"); 
    } 
    return 0; 
} 

顯示與n=4

Generate tables upto:4 
Table 1x  2x  3x  4x  5x  6x  7x  8x  9x  10x 
2  2  4  6  8  10  12  14  16  18  20 
3  3  6  9  12  15  18  21  24  27  30 
4  4  8  12  16  20  24  28  32  36  40 
+0

只是一個小事情,我卡住了我想要輸出來的表我要這個表寫在表下。我是一個初學者請與我聯繫 –

+0

我很樂意幫助你,但[編輯]你的問題,以顯示如何格式化輸出,因爲你的解釋不清楚。 –

+0

我已經接受你的回答,現在我正在尋找你的幫助 –

1

數組索引從0開始,上升到n-1,所以你正在訪問undefined behaviour的界限。

所以,你需要重寫循環爲:

for(i=0; i < n; i++) { 
    for(j=0; j < 10; j++) { 
     tables[i][j] = (i+1)*(j+1); 
     printf("%d\t", tables[i][j]); 
    } 
} 
相關問題