On XY plane, you are given upper left corner coordinates of two equal sized rect
ID: 3702755 • Letter: O
Question
On XY plane, you are given upper left corner coordinates of two equal sized rectangles. Find the intersection percentage of the rectangles.
Question: Write a program that is going to read two rectangle information and find the intersection percentage.
Input specification
You will be first given the width (w) and height (h) of the rectangles. Then upper left coordinates (x, y) of the two rectangles are given in the following two lines where 0 <= (x, y) <= 10000 and 1 <= (w, h) <= 100.
Output specification
Show a floating point number with 3 decimal places that is the intersection percentage to the second rectangle.
Input
4 3
1 4
3 5
Output
33.333
note:use in c++ while, for , if loops ,do not use return or calculation
Explanation / Answer
Hello,
Below is the program for your question -
int main(int argc, const char * argv[])
{
int width,height,xA1,yA1,xB1,yB1;
cin>>width>>height; // input width and height
cin>>xA1>>yA1; //input 1st rectangle coordinates
cin>>xB1>>yB1; //input 2nd rectangle coordinates
// bottom most coordinates of 1st rectangle
int xA2=xA1-width;
int yA2=yA1-height;
// bottom most coordinates of 2nd rectangle
int xB2=xB1-width;
int yB2=yB1-height;
int area=(width*height);
int widthIntersection;
int heightIntersection;
int areaIntersection=0;
float intersectionPercentage=0.0
if(yA1<yB2 || yB1<yA2 || xA1<xB2 || xB1<xA2){ // to check if rectangles will intersect.
fixed << setprecision(3)<<intersectionPercentage;
}
else{
widthIntersection=abs(max(xA2,xB2)-min(xA1,xB1));
heightIntersection=abs(max(yA2,yB2)-min(yA1,yB1));
areaIntersection=widthIntersection*heightIntersection;
int unionArea=2*area-2*areaIntersection-areaIntersection;
intersectionPercentage=((float)areaIntersection/(float)unionArea)*100;
cout<< fixed << setprecision(3)<<intersectionPercentage;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.