用java编写一个求三角形面积的代码
时间: 2024-09-22 17:09:42 浏览: 45
在Java中,计算三角形面积的一个简单方法是基于海伦公式或者基础边长乘以对应高的方法。这里给出两种常见的做法:
1. **使用基础边长和高**:
```java
public class TriangleArea {
public static double calculateTriangleArea(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
double base = 5.0; // 三角形底边长度
double height = 3.0; // 三角形对应的高度
double area = calculateTriangleArea(base, height);
System.out.println("The area of the triangle is " + area + " square units.");
}
}
```
2. **使用海伦公式** (适用于已知三边的情况),对于任意三角形,可以先计算半周长,然后应用公式`area = sqrt[p*(p-a)*(p-b)*(p-c)]`,其中a、b、c是三角形的三个边长,p是半周长((a+b+c)/2):
```java
import java.util.Scanner;
public class TriangleAreaHeron {
public static double calculateHeronArea(double a, double b, double c) {
double semiperimeter = (a + b + c) / 2;
double area = Math.sqrt(semiperimeter * (semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c));
return area;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter side a: ");
double a = scanner.nextDouble();
System.out.print("Enter side b: ");
double b = scanner.nextDouble();
System.out.print("Enter side c: ");
double c = scanner.nextDouble();
double area = calculateHeronArea(a, b, c);
System.out.println("The area of the triangle is " + area + " square units.");
}
}
```
阅读全文