您的位置:首页 > 编程语言

C和指针之数组编程练习3(判断矩阵是否为单位矩阵)

2017-11-12 23:57 316 查看

1、题目

3.单位矩阵就是一个正方形矩阵,它除了主对角线元素值为1以外,其余元素的值均为0,例如:

 *1 0 0

 *0 1 0

 *0 0 1

 *就是一个3×3单位矩阵,编写一个名叫identity_matrix的函数,它接受一个10×10整型矩阵为参数

 *成功返回1,失败返回1

4、修改前一个问题中的identity_matrix函数,它可以对数组进行扩展,从而能够接受任意大小的矩阵参数。函数的第一个参数应该是一个整型指针,你需要第二个参数,用于指定矩阵的大小。
  



2、代码实现

#include <stdio.h>
/*
*3.单位矩阵就是一个正方形矩阵,它除了主对角线元素值为1以外,其余元素的值均为0,例如:
*1 0 0
*0 1 0
*0 0 1
*就是一个3×3单位矩阵,编写一个名叫identity_matrix的函数,它接受一个10×10整型矩阵为参数
*成功返回1,失败返回1
**/
int identity_matrix(int (*matrix)[10]){
for (int i = 0; i < 10; ++i)
for (int j = 0; j < 10; ++j)
{
if (i == j)
{
if (matrix[i][j] != 1)
return 0;
}
else
{
if (matrix[i][j] != 0)
return 0;
}
}
return 1;
}

/**4、修改前一个问题中的identity_matrix函数,它可以对数组进行扩展,从而能够接受任意大小的矩阵参数。
*    函数的第一个参数应该是一个整型指针,你需要第二个参数,用于指定矩阵的大小。
*
*/

int identity_matrix1(int *matrix,int n){
int row;
int column;
for (row = 0; row < n; row++)
{
for (column = 0; column < n; column++)
{
if (*matrix++ != (row == column))
return 0;
}
}
return 1;
}

int main()
{
int matrix[10][10] = {{1, 0}, {1}, {1}, {1}, {1},
{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1}, {1}};
int result = identity_matrix(matrix);
printf("result is %d\n", result);
int result1 = identity_matrix1(matrix, 10);
printf("result1 is %d\n", result1);
return 0;
}


3、运行结果

1111deMacBook-Pro:dabian a1111$ vim identity_matrix.c
1111deMacBook-Pro:dabian a1111$ gcc -w -g identity_matrix.c -o identity_matrix
1111deMacBook-Pro:dabian a1111$ ./identity_matrix
result is 0
result1 is 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: