矩形变量in和range的给定值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]范围内。如果为true,则增加此类对的计数。
采取类型为pair <int,int>的数组rec []。
首先和最后两个变量来定义范围。
函数ratio_sides(pair <int,int> rec [],int total,double first,double last)接受矩形的边并返回矩形数目的计数,以使边的比率在[a,b]范围内。
将初始计数设为0。
使用从i = 0到i <total的for循环遍历。
在对rec [i]中提取更大的值,因为maxi = max(rec [i] .first,rec [i] .second)。
将对rec [i]中的较小值提取为mini = min(rec [i] .first,rec [i] .second)。
计算平均值=最大/最小。
如果平均值的值在[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