c - 如何检查方阵主对角线的元素是否相同?

标签 c arrays matrix multidimensional-array

我必须编写一个程序,使用以下函数检查方阵 (n x n) 主对角线中的元素(数字)是否相同(如果相同则返回 1,否则返回 0)由main()调用。矩阵是从文件中读取的,在 main() 中完成。

这是到目前为止我的函数:(函数checkdiag()似乎不起作用,只有main()函数正在打印数据)

#include <stdio.h>
int checkdiag(int matrix[][100], int size)
{
    int i,j;
    for (i=0; i<size; i++)
    {
        for (j=0; j<size; j++)
        {
            if (matrix[i][100]==matrix[j][100])
            {
                return (1);
                printf ("\nThe elements in the main diagonal of the matrix are the same.\n");
            }
            else
            {
                return (0);
                printf ("\nThe elements in the main diagonal are not the same.\n");
            }
        }
    }
}
int main (void)
{
    int matrix[100][100];
    int size, diag;
    int i,j;
    FILE *data;
    data= fopen("data10.txt", "r");`

    fscanf (data, "%d", &size);
    printf ("The size of the matrix is %dx%d, and the matrix is:\n", size, size);
    for (i=0; i<size; i++)
    {
        for (j=0; j<size; j++)
        {
            fscanf (data, "%d", &matrix[i][j]);
            printf (" %d% ", matrix[i][j]);
        }
        printf ("\n");
    }
    diag= checkdiag(matrix, size);
}

如果有人可以帮我看看我哪里出了问题,我将不胜感激!

P.S 我正在使用的文件是:

3
4 5 6
7 8 9
3 6 7

其中文件 (3) 中的第一个值是矩阵的大小。 (即 3x3)

最佳答案

#include <stdio.h>

int main (void){

FILE *file = fopen("data.txt","r");
int size, i, j;

fscanf(file, "%d" , &size);
int matrix[size][size];

// Read the data into the matrix
for(i=0; i<size; i++){
    for(j=0; j<size; j++){
        fscanf(file, " %d", &matrix[i][j] );
    }
}

//determine if all diagonal entries in the matrix match the one at matrix[0][0]
i=matrix[0][0];
j=0;
while(j < size ){
    if(matrix[j][j] != i)
        break;
    else{
        j++;
    }
}

//if j is equal to the size of the matrix then voila! diagonal entries match.
if(j==size){
    printf("The diagonal is the same\n");
    return 1;
}else{
    printf("The diagonal is not the same\n");
    return 0;
}
}

返回:对角线不相同。对于输入:

5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 2

返回:对角线相同。对于输入:

5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 1

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

相关文章:

c# - 多维列表 C#

javascript - jquery 从数组中选择每个元素

r - 在 R 中展开矩阵的列

r - 如何对 R 中多个矩阵列表的相同单元格进行平均

c - C 中的结构填充

c - 数字输入的段错误

c - 在数组中分配唯一的随机整数 (C)

ios - 生成一个介于 0 和 1 之间的随机 float

javascript - AngularJS如何获取 bool 值

java - 确定矩阵是否是魔法矩阵