在C ++中的特殊矩阵中计数等于x的条目
矩阵就像二维数组,其中数字或元素表示为行和列。
因此,让我们借助示例了解问题的解决方案-
输入-
matrix[row][col] = {
{1, 2, 3},
{3, 4, 3},
{3, 4, 5}};
x = 3输出-
Count of entries equal to x in a special matrix: 4
输入-
matrix[row][col] = {
{10, 20, 30},
{30, 40, 30},
{30, 40, 50}};
x = 30输出-
Count of entries equal to x in a special matrix: 4
在以下程序中使用的方法如下
以矩阵mat[][]和x作为输入值。
在函数计数中,我们将对条目数进行计数。
遍历整个矩阵,在其中找到mat[i][j]==x的值,然后将计数增加1。
返回count的值并作为结果打印。
示例
#include<bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
//计算等于X的条目
int count (int matrix[row][col], int x){
int count = 0;
//遍历并查找因素
for(int i = 0 ;i<row;i++){
for(int j = 0; j<col; j++){
if(matrix[i][j] == x){
count++;
}
}
}
//返回计数
返回计数;
}
int main(){
int matrix[row][col] = {
{1, 2, 3},
{3, 4, 3},
{3, 4, 5}
};
int x = 3;
cout<<"Count of entries equal to x in a special matrix: "<<count(matrix, x);
return 0;
}输出结果
如果运行上面的代码,我们将获得以下输出-
Count of entries equal to x in a special matrix: 4