avatar
fireworks99
keep hungry keep foolish

判断矩形相交

int check(int x1,int y1,int x2,int y2,int x3, int y3,int x4, int y4)
{
    if(x2 < x3 || x4 < x1 || y4 < y1 || y2 < y3)
        return 0;
    return (min(y4, y2)- max(y1,y3)) * (min(x4,x2) - max(x1, x3));
}

上面那个代码好垃圾,只能用在一种特定情况下:

先输入左下角坐标,后输入右上角坐标

要是先输入右上角坐标,再输入左下角坐标呢?

要是输入左上角坐标跟右下角坐标呢?

Code

double x1, y1, x2, y2, x3, y3, x4, y4, lux, luy, rdx, rdy;
    scanf("%lf%lf%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
    lux = max(min(x1,x2),min(x3,x4));
    luy = max(min(y1,y2),min(y3,y4));
    rdx = min(max(x1,x2),max(x3,x4));
    rdy = min(max(y1,y2),max(y3,y4));
    if(rdx > lux && rdy > luy)
        printf("%.2f\n",(rdx - lux)*(rdy - luy));
    else
        printf("0.00\n");
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy