C程序设计(第四版) 谭浩强 例3.4
例3.4 给出三角形的三边长,求三角形面积。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
double a, b, c, s, area;
printf("Enter the side length of the triangle(a b c): ");
scanf_s("%lf %lf %lf", &a, &b, &c);
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("Area = %.2lf\n", area);
system("pause");
return 0;
}
方法2:使用函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//三角形三边检查,当2条边之和小于等于第3条边,三角形不成立
bool checkSide(double *side){
if(side[0] >= (side[1] + side[2]) || side[1] >= (side[0] + side[2]) || side[2] >= (side[0] + side[1])){
return false;
}
return true;
}
//输入函数
void input(double *triangle){
printf("Enter the side length of the triangle(a b c): ");
for(int i = 0; i < 3; i++){
scanf_s("%lf", &triangle[i]);
}
//非三角形报错,重新输入
while(checkSide(triangle) == false){
printf("Error! It's not a triangle! Retry!\n");
printf("Enter the side length of the triangle(a b c): ");
for(int i = 0; i < 3; i++){
scanf_s("%lf", &triangle[i]);
}
}
}
//三角形面积函数
double area(double *triangle){
triangle[3] = 0;
for(int i = 0; i < 3; i++){
triangle[3] += triangle[i] / 2;
}
double temp = triangle[3];
for(int i = 0; i < 3; i++){
temp *= (triangle[3] - triangle[i]);
}
return sqrt(temp);
}
int main(){
double *triangle = (double*)malloc(4 * sizeof(double));
input(triangle);
printf("Area = %.2lf\n", area(triangle));
free(triangle);
system("pause");
return 0;
}