解决代码:
import java.awt.Point;
import java.text.DecimalFormat;
import java.util.Scanner;
public class T_2036 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
//获得该图形的点数
int x = input.nextInt();
if (x == 0) {
return;
}
//初始化点的坐标
Point[] locations = new Point[x];
for (int i = 0; i < x; i++) {
Point p = new Point();
p.x = input.nextInt();
p.y= input.nextInt();
locations[i]=p;
}
//结果
double result = 0;
//进行数学公式计算面积
for (int i = 0; i < locations.length ; i++) {
result += 1.0*locations[i%x].x*locations[(i+1)%x].y-1.0*locations[(i+1)%x].x*locations[i%x].y;
}
//格式化输出结果
result = formatNum(result/2);
System.out.println(result);
}
}
/**
*四舍五入 保留两位小数
* @param num
* @return
*/
static double formatNum(double num) {
DecimalFormat df = new DecimalFormat("#.00");
return Double.parseDouble(df.format(num));
}
}
学到的知识:
公式-多边形求面积
例如三角形的三个点,p1 p2 p3 ,根据该公式求面积过程为 [(p1.x*p2.y-p2.x*p1.x)+(p2.x*p3.y-p3.x*p2.y)+(p3.x*p1.y-p1.x*p3.y)]/2