Java黑皮书课后题第2章:*2.19(几何:三角形面积)编写程序,提示用户输入三角形的三个点(x1, y1)(x2, y2)(x3, y3),然后显示它的面积
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第2章:*2.19(几何:三角形面积)编写程序,提示用户输入三角形的三个点(x1, y1)(x2, y2)(x3, y3),然后显示它的面积
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
*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);筆者思路(這是求邊的,默認都知道兩點之間距離公式):
從外向里,從左到右,逐步深入
總結
以上是生活随笔為你收集整理的Java黑皮书课后题第2章:*2.19(几何:三角形面积)编写程序,提示用户输入三角形的三个点(x1, y1)(x2, y2)(x3, y3),然后显示它的面积的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第2章:2.18(打
- 下一篇: Java黑皮书课后题第2章:*2.20(