为什么我的二维数组打印出不正确的值?

时间:2019-03-14 23:09:21

标签: c arrays multidimensional-array

我正在尝试打印第1、4和6列的总和。 当我在二维数组中输入30个字符时,结果如下:

Sum of 1st column is: 6
Sum of 1st column is: 12
Sum of 1st column is: 18
Sum of 1st column is: 24
Sum of 1st column is: 30
Sum of 4th column: 3
Sum of 4th column: 6
Sum of 4th column: 9
Sum of 4th column: 12
Sum of 4th column: 15
Sum of 6th column is: 1
Sum of 6th column is: 2
Sum of 6th column is: 3
Sum of 6th column is: 4
Sum of 6th column is: 5
#include <stdio.h>

int main()
{
    int i, j, sum1=0, sum2=0, sum3=0, arr[5][6];
    int value;

    for(i=0; i < 5; i++){
        for(j=0; j<6; j++){
            printf("Enter a value: ");
            scanf("%d",&value);
            arr[i][j]=value;
        }
    }

    printf("Two Dimensional array elements:\n");
    for(i=0; i<5; i++) {
      for(j=0;j<6;j++) {
         printf("%d ", arr[i][j]);
         if(j==5){
            printf("\n");
         }
       }
    }

    //this functions calculate the sum of the 1st column//
    for(i=0; i<5; i++){
        for(j=0; j<6; j++){
            sum1 = arr[i][j] + sum1;
        }
        printf("Sum of 1st column is: %d\n", sum1);
    }

    //this functions calculate the sum of the 4th column//
    for(i=0; i<5; i++){
        for(j=3; j<6; j++){
            sum2 = arr[i][j] + sum2;
        }
        printf("Sum of 4th column: %d\n", sum2);
    }

    //this functions calculate the sum of the 6th column//
    for(i=0; i<5; i++){
        for(j=5; j<6; j++){
            sum3 = arr[i][j] + sum3;
        }
        printf("Sum of 6th column is: %d\n", sum3);
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

根据您的printfs,我假设您要打印 1、4、6的总和。

为简单起见,我们只考虑第0列-您可以轻松地扩展它。

您有一个2D数组,并且想要第0列中的数字总和。考虑如何迭代遍历数组以实现此目的。您想将列固定为0,而只增加行数-有意义吗?

这是执行此操作的许多方法之一:

//this functions calculate the sum of the 1st column//
    for(i=0; i<5; i++){
    sum1 = arr[i][0] + sum1;
    }
printf("Sum of 1st column is: %d\n", sum1);

这有意义吗?

答案 1 :(得分:0)

基本上,StoneThrow已经说明了原因,但是关于循环的代码似乎存在错误,例如,在添加第一列的第一个循环中,实际上是在添加整个矩阵,因为增加行数和列数。

代码应如下所示:

//Addition for column one
for(i=0;i<5;i++){
    sum1=arr[i][0]+sum1;
    printf("Sum of 1st column is: %d\n", sum1);
}

//Addition for column four
for(i=0;i<5;i++){
    sum2=arr[i][3]+sum2;
    printf("Sum of the 4th column is: %d\n", sum2);
}

//Addition for column six
for(i=0;i<5;i++){
    sum3=arr[i][5]+sum3;
    printf("Sum of the 6th column is: %d\n", sum3);
}

因此,只需小心循环,就不必嵌套它们,因为您实际上只是将数组的一组用作变量,而另一组用作常量。