C++计算两个矩形重叠面积

#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
inline LL read()
{
    int  c=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){c=c*10+ch-'0';ch=getchar();}
    return c*f;
}
int main()
{
    double x[4],y[4],x1,y1,x2,y2;
    while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf",x,y,x+1,y+1,x+2,y+2,x+3,y+3)!=EOF)
    {
        x1=fabs(x[1]-x[0]),y1=fabs(y[1]-y[0]),x2=fabs(x[2]-x[3]),y2=fabs(y[2]-y[3]);sort(x,x+4),sort(y,y+4);
        if(x[3]-x[0]<x1+x2&&y[3]-y[0]<y1+y2) printf("%.2f\n",(x[2]-x[1])*(y[2]-y[1]));
        else puts("0.00");
    }
    return 0;
}

有bug:

#include <stdio.h>
float x1, x2, x3, x4, y1, y2, y3, y4, s;  //定义输入的数和面积 
float x_1, x_2, x_3, x_4, y_1, y_2, y_3, y_4;

int main()
{
    while(scanf("%f %f %f %f %f %f %f %f", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4) != EOF){
        //转换为左上角和右下角的坐标 
        if(x1 <= x2 && y1 >= y2) {
            x_1 = x1;
            x_2 = x2;
            y_1 = y1;
            y_2 = y2;
        }
        if(x2 <= x1 && y2 >= y1){
            x_1 = x2;
            x_2 = x1;
            y_1 = y2;
            y_2 = y1;
        }
        if(x1 <= x2 && y1 <= y2){
            x_1 = x1;
            x_2 = x2;
            y_1 = y2;
            y_2 = y1;
        }
        if(x1 >= x2 && y1 >= y2){
            x_1 = x2;
            x_2 = x1;
            y_1 = y1;
            y_2 = y2;
        }
        //第二个矩形 
        if(x3 <= x4 && y3 >= y4) {
            x_3 = x3;
            x_4 = x4;
            y_3 = y3;
            y_4 = y4;
        }
        if(x4 <= x3 && y4 >= y3){
            x_3 = x4;
            x_4 = x3;
            y_3 = y4;
            y_4 = y3;
        }
        if(x3 <= x4 && y3 <= y4){
            x_3 = x3;
            x_4 = x4;
            y_3 = y4;
            y_4 = y3;
        }
        if(x3 >= x4 && y3 >= y4){
            x_3 = x4;
            x_4 = x3;
            y_3 = y3;
            y_4 = y4;
        }
        //计算 
        if(x_3 >= x_1 && x_3 <= x_2 && y_3 >= y_2 && y_3 <= y_1){
            s = (x_2 - x_3) * (y_3 - y_2);
        }
        if(x_3 >= x_1 && x_3 <= x_2 && y_4 >= y_2 && y_4 <= y_1){
            s = (x_2 - x_3) * (y_1 - y_4);
        }
        if(x_4 >= x_1 && x_4 <= x_2 && y_4 >= y_2 && y_4 <= y_1){
            s = (x_4 - x_1) * (y_1 - y_4);
        }
        if(x_4 >= x_1 && x_4 <= x_2 && y_3 >= y_2 && y_3 <= y_1){
            s = (x_4 - x_1) * (y_3 - y_2);
        }
        else puts("0.00")
        printf("%.2f\n", s);
    }
    return 0;
}


原文链接: https://www.cnblogs.com/Brimon-zZY/p/13969711.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/205054

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午10:04
下一篇 2023年2月12日 下午10:05

相关推荐