2016-09-23 74 views
0

我試圖在C中求和列。我的代碼只添加第一列的總和,例如,如果是2x2數組,它只添加第一列但剩下的它顯示奇怪的數字。這是我到目前爲止。我還沒有做出行的代碼。謝謝你的幫助。總結c列中的垃圾數

#include <stdio.h> 

int main(){ 


printf("Enter the number of columns"); 
int i; 
scanf("%d", &i); 
printf("Enter the number of rows"); 
int y; 
scanf("%d", &y); 

int r[i][y]; 
int a; 
int b; 
int columntotal[i],rowtotal[y]; 

for (a=0; a<i; a++){ 
    for (b=0; b<y; b++){ 
    scanf("%d",&r[a][b]); 
    } 
} 


//printing 
for(a=0;a<i;a++) 
{ 
    for(b=0;b<y;b++){ 

     printf("\t%d", r[a][b]); 

    } 
printf("\n"); 
} 




for (a=0;a<i;a++){ 
    for (b=0;b<y;b++){ 
     columntotal[a]=columntotal[a]+r[a][b]; 

    } 
} 
for (a=0;a<i;a++){ 
    printf("%d\n", columntotal[a]); 
} 

return(0); 
} 
+3

C數組通常排列爲'array [rows] [cols]'。你需要在使用之前初始化'columntotal'數組。當你在一個函數內聲明一個變量(數組或其他)時,該變量的起始值是不確定的,直到你給它賦值爲止。 – user3386109

+0

'int columntotal [i];' - >'int columntotal [i] = {0};' – chux

回答

0

至於我記得動態行,列分配而創建數組中C.So是不可能的這份聲明int columntotal[i],rowtotal[y];不會工作,除非我,y是即#define i,y,etc一個常數變量,它是不是在你的情況。

其次,您正在迭代未正確聲明的columntotal數組。您可以利用動態內存分配將塊數分配到columntotal array,然後在迭代時使用列總和填充它。

int *columntotal= malloc(i * sizeof (int)); 
for (a=0;a<i;a++){ 
    for (b=0;b<y;b++){ 
    columntotal[a]=columntotal[a]+r[a][b]; //r is your 2D array 

    } 
}