已知三角形的三边长,编程实现求三角形面积的功能函数。
时间: 2024-03-15 07:44:12 浏览: 48
下面是一个 Python 的例子,可供参考:
```python
import math
def triangle_area(a, b, c):
# 计算半周长
p = (a + b + c) / 2
# 使用海伦公式计算面积
area = math.sqrt(p * (p - a) * (p - b) * (p - c))
return area
```
这个函数接受三个参数a、b、c,分别表示三角形的三条边长。函数内部先计算出半周长p,然后使用海伦公式计算三角形的面积,并返回结果。需要先导入 Python 自带的 math 模块,以使用 sqrt 函数来计算平方根。
相关问题
用Python编写函数,已知三角形三边边长,求面积
可以使用海伦公式来计算三角形的面积,公式如下:
s = (a + b + c) / 2
area = sqrt(s * (s - a) * (s - b) * (s - c))
其中,a、b、c 分别为三角形的三条边长,s 为半周长,即 s = (a + b + c) / 2。
下面是使用 Python 编写的函数代码:
```python
from math import sqrt
def triangle_area(a, b, c):
s = (a + b + c) / 2
area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
```
使用时,直接调用 `triangle_area` 函数,传入三角形的三条边长即可:
```python
>>> triangle_area(3, 4, 5)
6.0
```
这里以 (3, 4, 5) 为例,计算出来的面积应该为 6。
用C语言写已知三角形三边长 求三角形面积
可以使用海伦公式来计算已知三角形三边长时的面积。
海伦公式:设三角形三边长分别为a、b、c,p=(a+b+c)/2,则三角形面积S=sqrt(p(p-a)(p-b)(p-c))。
以下是一个使用C语言实现海伦公式计算三角形面积的例子:
```c
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, p, s;
printf("请输入三角形三边长:\n");
scanf("%f %f %f", &a, &b, &c);
p = (a + b + c) / 2;
s = sqrt(p * (p - a) * (p - b) * (p - c));
printf("三角形面积为:%f\n", s);
return 0;
}
```
在上面的例子中,使用了`scanf()`函数从控制台读取输入的三角形三边长,然后计算出三角形的面积并使用`printf()`函数输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)