介绍
在几何学中,三角形的面积定义为三角形边界内的空间大小。计算三角形面积的方法有多种,但其中最常见的两种方法是使用三角形的底和高,或使用海伦公式(Heron's formula),该公式以三角形的三条边作为输入。
在本实验中,你将学习如何编写 C 程序,使用这两种方法来计算三角形的面积。
使用底和高的基础程序
以下程序使用三角形的底和高来计算三角形的面积。
#include<stdio.h>
int main()
{
int h, b;
float area;
// 输入三角形的高和底
printf("Enter the height of the Triangle: ");
scanf("%d", &h);
printf("Enter the base of the Triangle: ");
scanf("%d", &b);
// 计算三角形的面积
area = (h*b)/(float)2;
// 输出三角形的面积
printf("The area of the triangle is: %f", area);
return 0;
}
解释:
- 我们引入了
stdio.h库以使用标准输入输出函数。 - 我们定义了
main函数并声明了一些变量h、b和area。 - 我们使用
scanf函数从用户那里获取三角形的底和高。 - 然后我们使用公式
(高 x 底)/2计算三角形的面积。 area = (h*b)/(float)2由于将分母值从int强制转换为float,因此结果会包含小数部分。- 最后,我们使用
printf函数输出三角形的面积。
使用海伦公式的高级程序
以下程序使用海伦公式(Heron's formula)计算三角形的面积。
#include<stdio.h>
#include<math.h>
int main()
{
double a, b, c, area, s;
// 输入三角形的三条边
printf("Enter the sides of the triangle:\n");
scanf("%lf%lf%lf", &a, &b, &c);
// 计算三角形的半周长 s
s = (a+b+c)/2;
// 使用海伦公式计算三角形的面积
area = sqrt(s*(s-a)*(s-b)*(s-c));
// 输出三角形的面积
printf("The area of the Triangle calculated using Heron's formula is: %lf", area);
return 0;
}
解释:
- 我们引入了
stdio.h和math.h库,分别用于标准输入输出函数和平方根函数。 - 定义了
main函数并声明了一些变量。 - 使用
scanf函数输入三角形的三条边。 - 使用公式
(a+b+c)/2计算三角形的半周长s。 - 使用海伦公式计算三角形的面积
area = sqrt(s*(s-a)*(s-b)*(s-c))。 - 最后,使用
printf函数输出三角形的面积。
在 main.c 中编写代码
现在,在 ~/project/ 目录下创建一个新文件 main.c,并复制前面步骤中的代码。
运行代码
要运行代码,只需打开终端并导航到 ~/project/ 目录,然后输入以下命令:
gcc main.c -o main
./main
main.c 的完整代码
#include<stdio.h>
#include<math.h>
int main()
{
// 第一步:使用底和高的基础程序
int h, b;
float area;
printf("Enter the height of the Triangle: ");
scanf("%d", &h);
printf("Enter the base of the Triangle: ");
scanf("%d", &b);
area = (h*b)/(float)2;
printf("The area of the triangle is: %f\n", area);
// 第二步:使用海伦公式的高级程序
double a, b, c, area2, s;
printf("Enter the sides of the triangle:\n");
scanf("%lf%lf%lf", &a, &b, &c);
s = (a+b+c)/2;
area2 = sqrt(s*(s-a)*(s-b)*(s-c));
printf("The area of the Triangle calculated using Heron's formula is: %lf\n", area2);
return 0;
}
总结
在本实验中,你学习了如何编写 C 程序,使用底和高方法以及海伦公式方法计算三角形的面积。你还学习了如何在 main.c 文件中编写代码,并在终端中编译和运行程序。



