判断矩形相交及求面积的交并集

判断矩形相交及求面积的交并集

定义一个平面矩形类,从键盘输入两个矩形,判断这两个矩形是否相交?计算两矩形并集、交集的面积。

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值