【求解】已知三角形各点坐标,求三角形面积。
各位大神,以下是我求三角形面积的代码,还请大神们看看哪里错了,我输入坐标后,最后结果都显示为1.0,神奇了。
import java.util.*;
class MyClass{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Please enter the pixel:");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
double side1 =Math.pow((Math.pow((x1-x2), 2)+Math.pow((y1-y2),2)),1/2);
double side2 =Math.pow((Math.pow((x2-x3), 2)+Math.pow((y2-y3),2)),1/2);
double side3 =Math.pow((Math.pow((x3-x1), 2)+Math.pow((y3-y1),2)),1/2);
double s =(side1 + side2 + side3)/2;
double area =Math.pow((s*(s-side1)*(s-side2)*(s-side3)),1/2);
System.out.println("The triangle area ia " + area);
}
}
------最佳解决方案--------------------1 Math 类里pow()的定义,public static double pow(double a,double b),要求传入的参数是double型的。
2 double side1 =Math.pow((Math.pow((x1-x2), 2)+Math.pow((y1-y2),2)),1/2);
看这语句,x1,x2,y1,y1都是double的,int 型字面量“2”转型为double 是2.0.
3 关键是那个 1/2,这个转换过程是 1 2都是int型字面量,程序先按整型计算1/2,结果是0,之后把这个0 转
成double型,结果是0.0.
4 所以楼主的代码相当于:
double side1 =Math.pow((Math.pow((x1-x2), 2)+Math.pow((y1-y2),2)),0);
算下来:
三个边都是1。
后面的计算面积的代码:
double area =Math.pow((s*(s-side1)*(s-side2)*(s-side3)),1/2);
相当于:
double area =Math.pow((s*(s-side1)*(s-side2)*(s-side3)),0);
所以这个area=1.0.
试试下面的代码:
import java.util.*;
public class CalculateTheAreaOfTriangle1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the pixel:");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double x3 = input.nextDouble();
double y3 = input.nextDouble();
double side1 =Math.pow((Math.pow((x1-x2), 2)+Math.pow((y1-y2),2)),1/2);
System.out.println("side 1 is "+side1);
double side2 =Math.pow((Math.pow((x2-x3), 2)+Math.pow((y2-y3),2)),1/2);
System.out.println("side 2 is "+side2);
double side3 =Math.pow((Math.pow((x3-x1), 2)+Math.pow((y3-y1),2)),1/2);
System.out.println("side 3 is "+side3);
double s =(side1 + side2 + side3)/2;
double area =Math.pow((s*(s-side1)*(s-side2)*(s-side3)),1/2);
System.out.println("The triangle area is " + area);
side1 =Math.pow((Math.pow((x1-x2), 2)+Math.pow((y1-y2),2)),1.0/2); //1/2 变成1.0/2或者(double)1/2)
System.out.println("side 1 is "+side1);
side2 =Math.pow((Math.pow((x2-x3), 2)+Math.pow((y2-y3),2)),1.0/2);
System.out.println("side 2 is "+side2);
side3 =Math.pow((Math.pow((x3-x1), 2)+Math.pow((y3-y1),2)),1.0/2);