蓝桥杯——矩形面积交(java)
大致思路:
获取矩形的四边在x轴和y轴上的位置,分别用八个变量获取。取得矩形的上边和下边,左边和右边,分别存储。如果两矩形相交,则有一矩形的一点在另一矩形的内部,如下图
用两个判断得出其矩形的点坐标,然后通过相减的出要求的小矩形的x和y,在相乘得出面积。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double n1 = input.nextDouble(); //n为第一个矩形的四个边
double n2 = input.nextDouble();
double n3 = input.nextDouble();
double n4 = input.nextDouble();
double m1 = input.nextDouble(); //m为第二个矩形的四个边
double m2 = input.nextDouble();
double m3 = input.nextDouble();
double m4 = input.nextDouble();
double maxnx,maxmx,minnx,minmx,x = 0,y = 0,maxny,minny,maxmy,minmy; //max和min来存储两矩形的左边、右边、上边、下边。
if(n1>n3){ //判断n的左边和右边
maxnx = n1;
minnx = n3;
}else{
maxnx = n3;
minnx = n1;
}
if(m1>m3){ //判断m的左边和右边
maxmx = m1;
minmx = m3;
}else{
maxmx = m3;
minmx = m1;
}
if(maxmx >= maxnx && minmx <= minnx){ //x轴上,一矩形在另一矩形内部
x = maxnx - minnx; //获取小矩形的x轴长度
}else if(maxnx >= maxmx && minnx <= minmx){
x = maxmx - minmx;
}else if(maxmx >= minnx && maxmx <= maxnx){ //如果不是
x = maxmx - minnx;
}else if(maxnx >= minmx && maxnx <= maxmx){
x = maxnx - minmx;
}
//从此处与上方一致,只是求的是y轴
if(n2>n4){
maxny = n2;
minny = n4;
}else{
maxny = n4;
minny = n2;
}
if(m2>m4){
maxmy = m2;
minmy = m4;
}else{
maxmy = m4;
minmy = m2;
}
if(maxmy >= maxny && minmy <= minny){
y = maxny - minny;
}else if(maxny >= maxmy && minny <= minmy){
y = maxmy - minmy;
}else if(maxmy >= minny && maxmy <= maxny){
y = maxmy - minny;
}else if(maxny >= minmy && maxny <= maxmy){
y = maxny - minmy;
}
double res = x*y; //用一变量存储答案
System.out.println(String.format("%.2f",res)); //保留两位小数
}
}
这里我用的是String类的format方法来保留两位小数(个人认为最简单)