2

I need to find the difference from the sum of odd columns and sum of the even rows in matrix.

I solved the problem, but the sum of the even rows is incorrect. Here is my code:

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

#define MAX 100

int main()
{
     int i, j, sumR=0, sumK=0, m=0, n=0, a[MAX][MAX];

     scanf("%d %d", &n, &m);

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

    for(i=0; i < n; i++)
    {
        for(j=0; j <n; j++)
        {
            if((j+1)%2)
            sumK += a[i][j];
            else if ((i+1)%2 == 0)
            sumR += a[i][j];
        }
    }
    printf("Sum col: %d, Sum row: %d, Difference: %d \n", sumK, sumR, sumK-sumR);
    return 0;
}

The code first reads the dimensions of the matrix, then reads the values in the matrix and then calculates the sum. For example this matrix is 4x4:

2 5 7 3
3 8 2 1
6 7 9 9
1 6 9 4

The sum of columns is 39, and the rows is 34, but my output for rows is 19. Why is 19? where is my mistake?

4

1 回答 1

1

You have logical bug, remove else at else if ((i+1)%2 == 0) because it consider row only when column is odd.

于 2014-01-09T12:09:48.713 回答