一个具有四个顶点的凸多边形被分为四个三角形,如图所示。 编写一个程序,提示用户输入四个顶点的坐标,然后以升序显示四个三角形的面积。

题目:
一个具有四个顶点的凸多边形被分为四个三角形,如图所示。
编写一个程序,提示用户输入四个顶点的坐标,然后以升序显示四个三角形的面积。
在这里插入图片描述

源代码如下:
package com;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.println(“Enter x1, y1, x2, y2, x3, y3, x4, y4:”);
double[][] points = new double[4][2];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
points[i][j] = in.nextDouble();
}
}
double array[]=getIntersectingPoint(points);
System.out.print(“Intersecting point: (”);
for(int i=0;i<2;i++) {
if (i == 1) {
System.out.print(array[i] + ") ");
} else {
System.out.print(array[i] + “,”);
}
}
double x=array[0];
double y=array[1];
double x1 = points[0][0];
double y1 = points[0][1];
double x2 = points[1][0];
double y2 = points[1][1];
double x3 = points[2][0];
double y3 = points[2][1];
double x4 = points[3][0];
double y4 = points[3][1];
double[] S=new double[4];
S[0]= Math.abs((x1y2+x2y+xy1-x1y-x2y1-xy2)/2);
S[1]=Math.abs((x1y4+x4y+xy1-x1y-x4y1-xy4)/2);
S[2]=Math.abs((x3y2+x2y+xy3-x3y-x2y3-xy2)/2);
S[3]=Math.abs((x3y4+x4y+xy3-x3y-x4y3-xy4)/2);
bubble(S);
System.out.println();
System.out.print("The areas are ");
for(int i=0;i<4;i++) {
if (i == 3) {
System.out.print(S[i]);
} else {
System.out.print(S[i] + " ");
}
}
}
public static double[] getIntersectingPoint(double[][] points){
double x1 = points[0][0];
double y1 = points[0][1];
double x2 = points[1][0];
double y2 = points[1][1];
double x3 = points[2][0];
double y3 = points[2][1];
double x4 = points[3][0];
double y4 = points[3][1];
double K1 = (y1-y3)/ (x1-x3);
double K2 = (y2-y4)/ (x2-x4);
double[] arr=new double[2];
double B1 = y1 - K1x1 ;
double B2 = y2 - K2
x2 ;
arr[0]= (B2 - B1) / (K1 - K2);
arr[1]= (B2 * K1 - B1 * K2) / (K1 - K2);
return arr;
}
public static void bubble(double[] S){
double temp;
for(int i = 0; i<S.length; i++){
for (int j = S.length-1; j > i; j–) {
if (S[j] < S[j - 1]) {
temp = S[j - 1];
S[j - 1] = S[j];
S[j] = temp;
}
}
}
}
}
在这里插入图片描述

本题相关交点知识可以看本人上一个博客。
主要的最后面积升序算法表示用的是冒泡排序,较为基础简单。
本文为原创,转载请注明出处。
如果本文对你有帮助,请给我一个赞。

发布了9 篇原创文章 · 获赞 9 · 访问量 2161

猜你喜欢

转载自blog.csdn.net/grandniu/article/details/105617653