在 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.