如何检查矩阵的反对角线上的项是否相同?

时间:2018-04-16 01:52:48

标签: c function matrix multidimensional-array diagonal

这是我到目前为止的代码。我相信它与checkdiag2函数本身有关,因为我看着程序按步骤运行,它从未进行过最后一次' if'声明。我不确定为什么。这是无效的条件吗?我之前用i分配了反对角线的第一个值。

#include <stdio.h>
#include <stdlib.h>
int checkdiag2 (int **m, int size);

int 
main(void)
{
int i, j, dim, result;
int **arr;
FILE *in;
in = fopen("matrix3.txt", "r");
fscanf(in, "%d", &dim);
arr = (int**) calloc(dim, sizeof(int*));
for (i=0; i<dim; ++i)
    arr[i] = (int*) calloc(dim, sizeof(int));
for (i=0; i<dim; ++i)
    for (j=0; j<dim; ++j)
        fscanf(in, "%d", &arr[i][j]);
result = checkdiag2(arr, dim);
if (result == 1)
    printf("The matrix is %dx%d and all the numbers on the antidiagonal are the same", dim, dim);
else
    printf("The matrix is %dx%d and all the numbers on the antidiagonal are NOT the same", dim, dim);
for (i=0; i<dim; ++i)
    free(arr[i]);
free(arr);
return(0);
}

int checkdiag2 (int **m, int size)
{
int i, j, count=0;
i = m[0][size];
for (i=0; i<size; ++i)
    for (j=0; j<size; ++j)
        if ((i+j)==size)
            if(m[i][j]==m[0][size])
                count=count+1;
if (count==size)
return(1);
else
return(0);
}

我使用的文件中的数据是

8 8 9 4 5 6 7 8 5 8 8 4 5 6 7 5 5 8 9 8 5 6 5 5 5 8 9 4 8 5 5 8 5 8 9 4 5 8 7 8 5 8 9 5 5 6 8 8 4 8 5 4 5 6 7 8 4 5 9 4 5 6 7 8 8

结果打印出反对角线不一样。

1 个答案:

答案 0 :(得分:1)

C中的数组索引是基于0的;因此,如果您的矩阵是NxN,则反对角线上任何元素的索引将总和为N-1,而不是N.

相关问题