今天咱们来判断三角形,这也是暑假程序设计技能实训的作业之一
由于double类型的精度和sqrt()方法本身的问题,实际开方的结果与真实结果有那么一丢丢误差,解决这种误差可以通过近似取值方法来解决
代码如下:
package test2; import java.lang.Math; import java.util.Scanner; class point { public double x=0; public double y=0; public point(double x1,double y1){ this.x=x1;this.y=y1; } } class Triangle { private double d=0,e=0,f=0; public Triangle() {} public Triangle(double a,double b,double c){ this.d=a;this.e=b;this.f=c; } void settri(point a,point b,point c) { d=Math.sqrt(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y))); e=Math.sqrt(((c.x-b.x)*(c.x-b.x))+((c.y-b.y)*(c.y-b.y))); f=Math.sqrt(((a.x-c.x)*(a.x-c.x))+((a.y-c.y)*(a.y-c.y))); } double fabs(double x){ if(x<=0) return x; else return 0-x; } void checkitout() { int g=0,zj=0,dy=0,db=0; if(d+e<f||f+e<d||d+f<e) {System.out.print("这三个点不能构成三角形\n");} else { System.out.print("这三个点可以构成三角形\n"); g=1; } if(g==1) { if(fabs((f*f)+(d*d)-(e*e))<=0.001||fabs((f*f)-(d*d)+(e*e))<0.001||fabs((f*f)+(d*d)-(e*e))<0.001) {zj=1;} if(d==e||f==e||d==f) {dy=1;} if(e==d&&e==f) {db=1;} if(db==1) {System.out.print("为等边三角形\n");} else if(dy==1) { if(zj==1) {System.out.print("为等腰直角三角形\n");} else {System.out.print("为等腰三角形\n");} } else if(zj==1) {System.out.print("为直角三角形\n");} if(db==0&&zj==0&&dy==0) { System.out.print("这是一个普通三角形\n"); } } } }; public class Class12 { public static void main(String[] args) { Triangle t=new Triangle(); double a,b; Scanner input=new Scanner(System.in); System.out.print("输入三个点\n"); System.out.print("x1:");a=input.nextDouble(); System.out.print("y1:");b=input.nextDouble(); point p1=new point(a,b); System.out.print("x2:");a=input.nextDouble(); System.out.print("y2:");b=input.nextDouble(); point p2=new point(a,b); System.out.print("x3:");a=input.nextDouble(); System.out.print("y3:");b=input.nextDouble(); point p3=new point(a,b); t.settri(p1,p2,p3); t.checkitout(); input.close(); } }
运行结果如下: