C语言检查矩阵是否为稀疏矩阵

在矩阵中,若数值为0的元素数目远远多于非0元素的数目,并且非0元素分布没有规律时,则称该矩阵为稀疏矩阵;

本文将使用C语言来检查矩阵是否为稀疏矩阵;如果矩阵中的0数超过(n*m)/2,则矩阵为稀疏矩阵,其中的n为矩阵的维数。

示例代码:

#include <stdio.h>
 
void main ()
{
    int matrix[10][10];
    int i, j, m, n;
    int sparse_counter = 0;
 
    printf("Enter the order of the matix \n");
    scanf("%d %d", &m, &n);
    printf("Enter the elements of the matix \n");
    for (i = 0; i < m; ++i)
    {
        for (j = 0; j < n; ++j)
        {
            scanf("%d", &matrix[i][j]);
            if (matrix[i][j] == 0)
            {
                ++sparse_counter;
            }
        }
    }
    if (sparse_counter > ((m * n) / 2))
    {
        printf("The given matrix is Sparse Matrix !!! \n");
    }
    else
        printf("The given matrix is not a Sparse Matrix \n");
    printf("There are %d number of Zeros.", sparse_counter);
}

程序运行效果如下:

Enter the order of the matix
3 3
Enter the elements of the matix
1 2 3
0 0 0
4 0 0
The given matrix is Sparse Matrix !!!
There are 5 number of Zeros.

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/check-if-a-matrix-is-a-sparse-matrix.html

分类: 计算机技术
推荐阅读:
Python实现将二进制码转换为格雷码 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code);本文将使用Python实现将二进制码转换为格雷码;
C语言生成范围内的随机数 给定一个范围,当前时间做为随机种子,使用C语言生成范围内的随机数;
PySide6详细中文教程 PySide6是在Python环境下的一套Qt6 API库。使用PySide6可以轻松创建基于Qt6的GUI程序;PySide6由Qt官方维护。
Linux显示使用内存最多的十个进程 在Linux系统下,你可以使用一条命令显示当前系统使用内存最多的十个进程:
使用pip安装Python PIL库的正确方法 正确使用pip工具安装Python中PIL库的方法如下:
如何查看硬盘序列号(S/N) 要在Windows系统上查看硬盘序列号只需要打开命令提示符【CMD】,运行以下命令:wmic diskdrive get model,serialnumber;黄色部分是你的硬盘名称,红色部分则是硬盘序列号;