海伦公式编写程序是什么

时间:2025-01-29 16:44:42 手机游戏

海伦公式用于计算三角形的面积,公式如下:

\[ s = \frac{a + b + c}{2} \]

\[ \text{area} = \sqrt{s \times (s - a) \times (s - b) \times (s - c)} \]

其中,\( s \) 是三角形的半周长,\( a \)、\( b \)、\( c \) 是三角形的三条边长。

C语言

```c

include

include

double calculateArea(double a, double b, double c) {

double s = (a + b + c) / 2;

double area = sqrt(s * (s - a) * (s - b) * (s - c));

return area;

}

int main() {

double a, b, c;

printf("请输入三角形的三条边长:\n");

scanf("%lf %lf %lf", &a, &b, &c);

double area = calculateArea(a, b, c);

printf("三角形的面积为:%.2lf\n", area);

return 0;

}

```

C++

```cpp

include

include

double calculateArea(double a, double b, double c) {

double s = (a + b + c) / 2;

double area = sqrt(s * (s - a) * (s - b) * (s - c));

return area;

}

int main() {

double a, b, c;

std::cout << "请输入三角形的三条边长:" << std::endl;

std::cin >> a >> b >> c;

double area = calculateArea(a, b, c);

std::cout << "三角形的面积为:%.1f" << std::endl;

return 0;

}

```

Python

```python

import math

def calculate_triangle_area(a, b, c):

s = (a + b + c) / 2

area = math.sqrt(s * (s - a) * (s - b) * (s - c))

return area

a = float(input("请输入三角形的第一条边长:"))

b = float(input("请输入三角形的第二条边长:"))

c = float(input("请输入三角形的第三条边长:"))

area = calculate_triangle_area(a, b, c)

print("三角形的面积为:", area)

```

Java

```java

import java.util.Scanner;

import java.lang.Math;

public class TriangleArea {

public static double calculateArea(double a, double b, double c) {

double s = (a + b + c) / 2;

double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));

return area;

}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("请输入三角形的三条边长:");

double a = scanner.nextDouble();

double b = scanner.nextDouble();

double c = scanner.nextDouble();

double area = calculateArea(a, b, c);

System.out.println("三角形的面积为:%.1f", area);

}

}

```

这些代码示例展示了如何使用不同编程语言实现海伦公式来计算三角形的面积。你可以选择适合你的编程语言进行尝试。