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

标签 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

结果显示反对角线不相同。

最佳答案

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

关于c - 如何检查矩阵反对角线上的项是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848628/

相关文章:

javascript - css 变换矩阵图像不保持相同的位置

c - C代码中的错误

c# - 函数正在传递变量的先前值而不是 Unity3D 中的当前值

php - function_exists 返回 false 但声明抛出错误

带有回调函数的jquery

c++ - opencv - 如何返回与比较矩阵相同类型的比较矩阵

java - 使用基本逻辑创建 N×N 对角矩阵

c - 如何转义 C 的 printf 中的 %(百分号)符号

c++ - 链接描述文件条件包含

c - 系统编程中链表的使用