题目:
编写一个方法,使用下面的方法头,返回一个三角形的面积:
public static double getTriangleArea(double[][] points)
三角形三个点的坐标(x1,y1)、(x2,y2)和(x3,y3)
保存在一个3 x 2的二维矩阵points中,
其中(points[0][0],points[0][1])代表(x1,y1)。
编写一个程序,提示用户输入三角形的三个点,然后显示三角形的面积。
程序源码如下:
package com;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.println(“请输入3个坐标的值:”);
double[][] points = new double[3][2];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
points[i][j] = in.nextInt();
}
}
getTriangleArea(points);
}
public static double getTriangleArea(double[][] points){
double b,c;
b=points[0][0]*points[1][1]-points[0][0]*points[2][1]+points[1][0]*points[2][1]-points[1][0]*points[0][1]+points[2][0]*points[0][1]-points[1][0]*points[1][1];
c=b/2;
double a = Math.abs( c) ;
System.out.println(“面积为:”);
System.out.println(a);
return 0;
}
}
得到三个点求面积的算法:
S=绝对值((x1y1-x1y3+x2y3-x2y1+x3y1-x2y2)/2)
注意y3是数组中的[2][1]
因为题目是public static double getTriangleArea(double[][] points)
所以是方法,不是类里面的成员方法,开始的时候写了好久,一直写在main的外面,定义了类,导致很简单的一道题花了很多时间,在网上查询了好久也没有找到结果,后来才想到,恍然大悟,虽是一道简单的小题,但自己写出来也是成就满满,这就是计算机的魅力吧,别放弃,加油!
此文为原创,转载请注明出处。
如对你有帮助,请给我一个赞!