在给定的矩阵中,当大多数元素为零时,我们称之为稀疏矩阵。 例如 - 3 x3 矩阵
1 1 0 0 0 2 0 0 0
在这个矩阵中,大部分元素都是零,所以它是一个稀疏矩阵。
检查一个矩阵是否是稀疏矩阵。
让我们假设矩阵中的零大于(行数 * 列数)/2。
那么,这个矩阵就是一个稀疏矩阵,否则不是。
以下是检查给定矩阵是否为稀疏矩阵的程序:
演示
#include<stdio.h> #include<stdlib.h> int main(){ int row,col,i,j,a[10][10],count = 0; printf("Enter row</p><p>"); scanf("%d",&row); printf("Enter Column</p><p>"); scanf("%d",&col); printf("Enter Element of Matrix1</p><p>"); for(i = 0; i < row; i++){ for(j = 0; j < col; j++){ scanf("%d",&a[i][j]); } } printf("Elements are:</p><p>"); for(i = 0; i < row; i++){ for(j = 0; j < col; j++){ printf("%d\t",a[i][j]); } printf("</p><p>"); } /*checking sparse of matrix*/ for(i = 0; i < row; i++){ for(j = 0; j < col; j++){ if(a[i][j] == 0) count++; } } if(count > ((row * col)/2)) printf("Matrix is a sparse matrix </p><p>"); else printf("Matrix is not sparse matrix</p><p>"); }
当执行上述程序时,会产生以下结果 -
Run 1: Enter row 3 Enter Column 2 Enter Element of Matrix1 1 0 2 0 2 0 Elements are: 1 0 2 0 2 0 Matrix is not sparse matrix Run 2: Enter row 3 Enter Column 2 Enter Element of Matrix1 1 0 0 0 0 0 Elements are: 1 0 0 0 0 0 Matrix is a sparse matrix
以上就是稀疏矩阵的C程序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号