问题描述
Given two rectangles and the coordinates of two points on the diagonals of each rectangle,you have to calculate the area of the intersected part of two rectangles. its sides are parallel to OX and OY .
输入
Input The first line of input is 8 positive numbers which indicate the coordinates of four points that must be on each diagonal.The 8 numbers are x1,y1,x2,y2,x3,y3,x4,y4.That means the two points on the first rectangle are(x1,y1),(x2,y2);the other two points on the second rectangle are (x3,y3),(x4,y4).
输出
Output For each case output the area of their intersected part in a single line.accurate up to 2 decimal places.
代码
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x1, x2, x3, x4, y1, y2, y3, y4;
double a, b, c, d;
double s;
while (cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4) {
s = 0;
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
if (x3 > x4) swap(x3, x4);
if (y3 > y4) swap(y3, y4);
if (x1 > x4 || x2 < x3 || y1 > y4 || y2 < y3) cout << "0.00" << endl;
else {
if (x1 <= x3) a = x3;
else a = x1;
if (x2 <= x4) c = x2;
else c = x4;
if (y1 <= y3) b = y3;
else b = y1;
if (y2 <= y4) d = y2;
else d = y4;
s = (c - a) * (d - b);
cout << fixed << setprecision(2) << s << endl;
}
}
return 0;
}
其中的 swap 函数也可以自己编写一个新的交换函数,大致的思想就是这样.之前没有AC的原因就是没有考虑 x1 > x4 || x2 < x3 || y1 > y4 || y2 < y3 的时候两个矩形相交的面积为0;面积的判断与计算大家可以在纸上动手随意画出两个矩形,标出对角线上的坐标即可.欢迎大家交流探讨.