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

分类: 计算机技术
推荐阅读:
PySide6控件教程中的一些约定 在本教程中,我们将介绍一些在PySide6中使用控件时的常用代码和内容约定,以帮助您编写易于理解、易于维护和高质量的GUI应用程序。
Golang中的map数据类型 map 是一堆键值对的未排序集合;在Go语言中,使用map不需要引入库,它是一种内置的数据类型。
Python使用集合实现内容去重 有这么一个场景,某个文件用于记录人名(也可以是URL或者其他的),编辑发现,出现了重复的内容。那么我们如何使用Python来进行去重呢?
使用requests发送HTTP请求(GET和POST) 使用 Requests 发送HTTP请求非常简单;确保Python程序一开始导入了Requests模块:
Rust中的函数 函数在所有编程语言中都非常普遍,也非常重要;在Rust中,可以使用 fn 关键字来声明一个函数;
VirtualBox的无缝模式真是太酷了 VirtualBox的无缝模式真的很酷,可以让虚拟机中的系统和Windows系统共享一个窗口,具体是个什么效果,请看下图: