*2.19(几何:三角形面积)编写程序,提示用户输入三角形的三个点横纵坐标值,然后显示它的面积
题目题目概述运行示例思路代码如何用嵌套的pow()写出两点距离公式题目
题目概述
2.19(几何:三角形面积)编写程序,提示用户输入三角形的三个点横纵坐标值(x1, y1)(x2, y2)(x3, y3),然后显示它的面积
计算三角形面积的公式(处理后):
s = (side1 + side2 + side3) / 2
area = Math.pow(s(s-side1)(s-side2)(s-side3), 0.5)
运行示例
Enter the coordinates of three points separated by spaces like x1 y1 x2 y2 x3 y3: 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is 33.6
思路
在上面处理过后的三角形面积公式其实已经“暴露”思路了(其实这道题算是非常简单的)
先求出三条边长度
根据三个长度求出s
再求出area
代码
import java.util.Scanner;public class Test2_19 {public static void main(String[] args) {// 接收输入(三个点x y坐标)Scanner input = new Scanner(System.in);System.out.println("Enter the coordinates of three points separated by spaces like x1 y1 x2 y2 x3 y3: ");double x1 = input.nextDouble(), y1 = input.nextDouble();double x2 = input.nextDouble(), y2 = input.nextDouble();double x3 = input.nextDouble(), y3 = input.nextDouble();// 求出三条边的长度double side1 = Math.pow((Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)), 0.5);double side2 = Math.pow((Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2)), 0.5);double side3 = Math.pow((Math.pow(x2 - x3, 2) + Math.pow(y2 - y3, 2)), 0.5);// 求s和areadouble s = (side1 + side2 + side3) / 2;double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);// 输出System.out.println("The area of the triangle is " + area);}}
如何用嵌套的pow()写出两点距离公式
double side1 = Math.pow((Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)), 0.5);
笔者思路(这是求边的,默认都知道两点之间距离公式):
从外向里,从左到右,逐步深入
最外面是根号,那么把根号里面的当做整体(用?表示),即为Math.pow(? ,0.5)①根号下还剩下Math.pow()+Math.pow(),且第二个参数都是2,那么我们将Math.pow(?, 2)+Math.pow(?, 2)带入表达式①,建议带入后前后加对括号这时结果为:Math.pow((Math.pow(?, 2)+Math.pow(?, 2)) ,0.5)那么还剩下(x1-x2)和(y1-y2),直接套对括号带入式子即可得到:Math.pow((Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)), 0.5)
Java黑皮书课后题第2章:*2.19(几何:三角形面积)编写程序 提示用户输入三角形的三个点(x1 y1)(x2 y2)(x3 y3) 然后显示它的面积
如果觉得《Java黑皮书课后题第2章:*2.19(几何:三角形面积)编写程序 提示用户输入三角形的三》对你有帮助,请点赞、收藏,并留下你的观点哦!