我试图在C中对列进行求和。我的代码只添加了第一列的总和,例如,如果是2x2数组,它只添加第一列,但其余部分则显示奇怪的数字。这是我到目前为止所得到的。我还没有为行创建代码。谢谢你的帮助。
#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);
}
答案 0 :(得分:0)
据我记得动态行,在C.中创建数组时无法进行col分配。因此,除非i,y是常量变量,即int columntotal[i],rowtotal[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
}
}