用 C++ 統計矩形數量,要求矩形長寬比在 [a,b] 範圍內。


給定矩形的邊長以及範圍變數 first 和 last。目標是找到長寬比在 [first, last] 範圍內的矩形數量。

例如

輸入

rec[] = { { 200, 210 }, { 100, 50 }, { 300, 190}, {180, 200}, {300, 200}} and first = 1.0, last = 1.6

輸出

Count of number of rectangles such that ratio of sides lies in the range [a,b] are: 4

解釋

The sides that have ratio in the range [ 1.0,1.6 ] are :
{200,210}, {300,190}, {180,200}, {300,200}

輸入

rec[] = { { 10,20 }, { 30, 10 }, { 100, 500}, {900, 300}, {450, 90}} and
first = 3.0, last = 4.0

輸出

Count of number of rectangles such that ratio of sides lies in the range [a,b]
are: 2

解釋

The sides that have ratio in the range [ 3.0,4.0 ] are :
{30,10}, {900,300}

下面程式中使用的演算法如下

在這個演算法中,我們將邊長儲存為 pair<int,int> 型別的陣列。對於每一對,檢查較大值/較小值的商是否在 [first, last] 範圍內。如果是,則增加此類對的數量。

  • 建立一個 pair<int,int> 型別的陣列 rec[]。

  • 建立兩個變數 first 和 last 來定義範圍。

  • 函式 ratio_sides(pair<int, int> rec[], int total, double first, double last) 接收矩形的邊長並返回矩形數量,要求矩形長寬比在 [a,b] 範圍內。

  • 初始計數為 0。

  • 使用 for 迴圈遍歷 i=0 到 i<total。

  • 在 pair rec[i] 中提取較大值為 maxi = max(rec[i].first, rec[i].second)。

  • 在 pair rec[i] 中提取較小值為 mini = min(rec[i].first, rec[i].second)。

  • 計算平均值 average=maxi/mini。

  • 如果 average 的值在 [first, last] 範圍內,則增加計數。

  • 在 for 迴圈結束時,返回計數作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int ratio_sides(pair<int, int> rec[], int total, double first, double last){
   int count = 0;
   for (int i = 0; i < total; i++){
      double maxi = max(rec[i].first, rec[i].second);
      double mini = min(rec[i].first, rec[i].second);
      double average = maxi/mini;
      if (average >= first){
         if(average <= last){
            count++;
         }
      }
   }
   return count;
}
int main(){
   pair<int, int> rec[] = { { 200, 210 }, { 100, 50 }, { 300, 190}, {180, 200}, {300, 200}};
   int total = 5;
   double first = 1.0, last = 1.6;
   cout<<"Count of number of rectangles such that ratio of sides lies in the range [a,b] are: "<<ratio_sides(rec, total, first, last);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count the number of rectangles such that ratio of sides lies in the range [a,b] are: 4

更新於: 2021年1月5日

164 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.