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

分类: 计算机技术
推荐阅读:
什么是控制字符? 控制字符是ASCII码表中的一部分字符,其编码在0到31之间(包括0和31),以及字符127;这些字符通常不用于显示文本,而是用于控制计算机的输入输出,或者用于传输数据时控制信息;
warning: implicit declaration of function 'getpid' 解决方法 在C程序中使用getpid()获取进程识别码时,可能会出现 warning: implicit declaration of function 'getpid'; did you mean 'getenv'? [-Wimplicit-function-declaration] 这样的警告信息;
Golang获取文件的大小 在Go语言中,你可以使用os.Stat()来获取文件信息,其中就包括文件的大小;
Python isinstance()函数 在Python中,isinstance()函数用于判断一个对象是否是指定类或类型的实例。
CreateThread()创建线程传递SOCKET参数 使用CreateThread()创建线程传递SOCKET参数的正确方法如下:
Python里with语句的用法与技巧 本文将详细讲解Python语言中with语句的用法,以及如何让自定义的类也支持with语句;