用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP