问题描述:
1、row == col时,如果p[row][col] == 1,它就是单位矩阵。
2、row != col时,如果p[row][col] == 0,它就是单位矩阵。
源代码:
1、用一级指针
#include< stdio.h>
#include<assert.h>
bool identity_matrix(int *p, int row, int col)
{
assert(p != NULL);
assert(row > 0 && col > 0);
for (int i = 0;i < row;++i)
{
for (int j = 0;j < col;++j)
{
if (i == j)
{
if (p[i*col+j] != 1)
{
printf("不是单位矩阵\n");
return false;
}
}
else
{
if (p[i*col+j] != 0)
{
printf("不是单位矩阵\n");
return false;
}
}
}
}
printf("是单位矩阵\n");
return true;
}
void main()
{
int arr[3][3] = { { 1,0,0 },{ 0,1,0 },{ 0,0,1 } };
identity_matrix((int *)arr, 3, 3);
}
2、用二级指针
#include< stdio.h>
#include<assert.h>
bool identity_matrix(int(*p)[3], int row, int col)
{
assert(p != NULL);
assert(row > 0 && col > 0);
for (int i = 0;i < row;++i)
{
for (int j = 0;j < col;++j)
{
if (i == j)
{
if (p[i][j] != 1)
{
printf("不是单位矩阵\n");
return false;
}
}
else
{
if (p[i][j] != 0)
{
printf("不是单位矩阵\n");
return false;
}
}
}
}
printf("是单位矩阵\n");
return true;
}
void main()
{
int arr[3][3] = { {1,0,0},{0,1,0},{0,0,1} };
identity_matrix(arr,3,3);
}