C语言 计算三角形的面积 ⭐️
一、方法 1:海伦公式 🍭


🦋 代码实现: 👇🏻
#include <stdio.h>
#include <math.h>int main() {double a, b, c; // 定义三角形的三条边printf("请输入三角形的三条边长:");scanf("%lf %lf %lf", &a, &b, &c);// 判断是否能构成三角形if (a + b > c && a + c > b && b + c > a) {double s = (a + b + c) / 2; // 计算半周长double area = sqrt(s * (s - a) * (s - b) * (s - c)); // 计算面积printf("三角形的面积为:%.2f\n", area);} else {printf("输入的三条边不能构成三角形!\n");}return 0;
}
请输入三角形的三条边长:3 4 5
三角形的面积为:6.00
二、方法 2:底边和高 🍭


🦋 代码实现: 👇🏻
#include <stdio.h>int main() {double base, height; // 定义底边和高printf("请输入三角形的底边和高:");scanf("%lf %lf", &base, &height);double area = 0.5 * base * height; // 计算面积printf("三角形的面积为:%.2f\n", area);return 0;
}
请输入三角形的底边和高:6 4
三角形的面积为:12.00
三、方法 3:已知三个顶点坐标 🍭


🦋 代码实现: 👇🏻
#include <stdio.h>
#include <math.h>int main() {double x1, y1, x2, y2, x3, y3; // 定义三个顶点的坐标printf("请输入三个顶点的坐标 (x1 y1 x2 y2 x3 y3):");scanf("%lf %lf %lf %lf %lf %lf", &x1, &y1, &x2, &y2, &x3, &y3);double area = 0.5 * fabs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)); // 计算面积printf("三角形的面积为:%.2f\n", area);return 0;
}
请输入三个顶点的坐标 (x1 y1 x2 y2 x3 y3):0 0 3 0 0 4
三角形的面积为:6.00
四、总结: 🍭

-
海伦公式:适用于已知三条边长的情况。
-
底边和高:适用于已知底边和对应高的情况。
-
顶点坐标:适用于已知三个顶点坐标的情况。

