【发布时间】:2021-03-09 10:38:38
【问题描述】:
我正在尝试通过函数检查两个矩阵是否相等。但我很困惑如何为函数EqualMatrices 编写参数。由于逻辑是比较相等或行和列如何在函数参数中传递这样的数组。
#include <stdio.h>
void EqualMatrices(int A[][10], int B[][10]) // how to write arguments for this function
{
/* Comparing two matrices for equality: this is the logic */
if (row1 == row2 && column1 == column2)
{
printf("Matrices can be compared \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < column2; j++)
{
if (a[i][j] != b[i][j])
{
flag = 0;
break;
}
}
}
}
else
{
printf(" Cannot be compared\n");
exit(1);
}
if (flag == 1)
printf("Two matrices are equal \n");
else
printf("But, two matrices are not equal \n");
}
void main()
{
int a[10][10], b[10][10];
int i, j, row1, column1, row2, column2, flag = 1;
printf("Enter the order of the matrix A \n");
scanf("%d %d", &row1, &column1);
printf("Enter the order of the matrix B \n");
scanf("%d %d", &row2, &column2);
printf("Enter the elements of matrix a \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < column1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix b \n");
for (i = 0; i < row2; i++)
{
for (j = 0; j < column2; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("MATRIX a is \n");
for (i = 0; i < row1; i++)
{
for (j = 0; j < column1; j++)
{
printf("%d", a[i][j]);
}
printf("\n");
}
printf("MATRIX b is \n");
for (i = 0; i < row2; i++)
{
for (j = 0; j < column2; j++)
{
printf("%d", b[i][j]);
}
printf("\n");
}
EqualMatrices(a, b);
return 0;
}
【问题讨论】:
-
首先将函数声明为
int EqualMatrices(int row1, int column1, int A[row1][column1], int row2, int column2, int B[row2][column2])。 -
请删除所有空行,避免可怕的水平滚动条。
-
我更喜欢在
string.h中使用memcmp,除非您有正当理由不这样做。