判断矩形相交及求面积的交并集
定义一个平面矩形类,从键盘输入两个矩形,判断这两个矩形是否相交?计算两矩形并集、交集的面积。
#include <iostream>
using namespace std;
class rectangle{
private:
float x1, y1, x2, y2;
public:
rectangle(){
x1 = y1 = x2 = y2 = 0;
}
rectangle(float x1, float x2, float x3, float x4){
x1 = x1;
x2 = x2;
x3 = x3;
x4 = x4;
}
~rectangle(){}
void in(){
cout <<"左下角的点坐标" <<endl;
cin >> x1 >> y1;
cout << "右上角的点坐标" <<endl;
cin >> x2 >> y2;
}
float getx1(){return x1;}
float gety1(){return y1;}
float getx2(){return x2;}
float gety2(){return y2;}
};
float getmin(float a, float b){
return a < b ? a : b;
}
float getmax(float a, float b){
return a > b ? a : b;
}
int main()
{
int flag = 0;
rectangle *p = new rectangle[2];
p[0].in();
p[1].in();
if(p[0].getx1() > p[1].getx2() || p[0].getx2() < p[1].getx1()||p[0].gety1() > p[1].gety2() ||p[0].gety2() < p[1].gety1())
cout << "两个矩形不相交" << endl;
else{
cout << "两个矩形相交" << endl;
flag = 1;
}
float narea;
float wide = getmin(p[0].getx2(), p[1].getx2()) - getmax(p[0].getx1(), p[1].getx1());
float height = getmin(p[0].gety2(), p[1].gety2()) - getmax(p[0].gety1(), p[1].gety1());
if(flag)
narea = wide * height;
else
narea = 0;
float uarea = (p[0].getx2() - p[0].getx1()) * (p[0].gety2() - p[0].gety1()) + (p[1].getx2() - p[1].getx1()) * (p[1].gety2() - p[1].gety1()) - narea;
cout << "面积的交集为: " << narea << endl;
cout << "面积的并集为: " << uarea;
return 0;
}