实施稀疏矩阵的 C++ 程序
稀疏矩阵是指其中大部分元素为 0 的矩阵。以下给出对此的一个示例。
下面给出的矩阵包含 5 个零。由于零的数量多于矩阵元素的一半,因此它是一个稀疏矩阵。
5 0 0 3 0 1 0 0 9
以下是一个用于实施稀疏矩阵的程序。
例如
#include<iostream>
using namespace std;
int main () {
int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} };
int i, j, count = 0;
int row = 3, col = 3;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j){
if (a[i][j] == 0)
count++;
}
}
cout<<"The matrix is:"<<endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"The number of zeros in the matrix are "<< count <<endl;
if (count > ((row * col)/ 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;
return 0;
}输出
The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix
在上面的程序中,使用嵌套 for 循环来计算矩阵中的零的数目。这通过以下代码段演示。
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
if (a[i][j] == 0)
count++;
}
}在找到零的数目后,使用嵌套 for 循环来显示矩阵。这在下面显示。
cout<<"The matrix is:"<<endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}最后,显示零的数目。如果零的数目大于矩阵中元素的一半,则显示矩阵是一个稀疏矩阵,否则该矩阵不是稀疏矩阵。
cout<<"The number of zeros in the matrix are "<< count <<endl; if (count > ((row * col)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl;
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP