定义一个三角形结构体,并构造函数实现三角形类型的判断和面积的计算。
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<math.h>
struct Triangle//三角形结构体
{
int edge1;
int edge2;
int edge3;
};
int setTri1(struct Triangle tri)//判断是否为三角形
{
if (tri.edge1 >= tri.edge2 + tri.edge3 || tri.edge2 >= tri.edge1 + tri.edge3 || tri.edge3 >= tri.edge1 + tri.edge2)
return 1;
else
{
return 0;
}
}
double area(struct Triangle tri)//计算三角形面积
{
double n = (tri.edge1 + tri.edge2 + tri.edge3) / 2.0;
double s = sqrt(n * (n - tri.edge1) * (n - tri.edge2) * (n - tri.edge3));
return s;
}
int judgeTri(struct Triangle tri)//判断三角形类型
{
if (tri.edge1 == tri.edge2 && tri.edge2 == tri.edge3)//等边三角形
return 0;
else
if (tri.edge1 == tri.edge2 || tri.edge1 == tri.edge3 || tri.edge2 == tri.edge3)//等腰三角形
return 1;
else
if ((tri.edge1 == sqrt(tri.edge2 * tri.edge2 + tri.edge3 * tri.edge3)) || (tri.edge2 == sqrt(tri.edge1 * tri.edge1 + tri.edge3 * tri.edge3)) || (tri.edge3 == sqrt(tri.edge2 * tri.edge2 + tri.edge1 * tri.edge1)))//直角三角形
return 2;
else
return 3;
}
int main()
{
struct Triangle tri = {0};
ll:
printf("请输入三条边\n");
scanf("%d %d %d", &tri.edge1, &tri.edge2, &tri.edge3);
if (setTri1(tri) == 1)
{
printf("不是三角形,请重新输入\n");
goto ll;
}
printf("面积是%f\n", area(tri));
if (judgeTri(tri) == 0)
printf("等边三角形\n");
else
if (judgeTri(tri) == 1)
printf("等腰三角形\n");
else
if (judgeTri(tri) == 2)
printf("直角三角形\n");
else
if (judgeTri(tri) == 3)
printf("普通三角形\n");
}