在 C++ 中统计特殊矩阵中等于 x 的条目数


给定一个方阵 mat[][],设矩阵元素为 mat[i][j] = i*j,任务是计算矩阵中等于 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 作为输入值。

  • 在 count 函数中,我们将计算条目的数量。

  • 遍历整个矩阵,当找到 mat[i][j] == x 的值时,将计数加 1。

  • 返回 count 的值并将其打印为结果。

示例

 在线演示

#include<bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
//count the entries equal to X
int count (int matrix[row][col], int x){
   int count = 0;
   // traverse and find the factors
   for(int i = 0 ;i<row;i++){
      for(int j = 0; j<col; j++){
         if(matrix[i][j] == x){
            count++;
         }
      }
   }
   // return count
   return 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

更新于:2020年6月6日

297 次查看

启动你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.