C++编码实现计算三角形面积
1- 计算公式
- 方法一: S=√[p(p-a)(p-b)(p-c)] ,而公式里的p为半周长:p=(a+b+c)/2
方法二: S=ah/2
- 方法三:
- 方法三:
2- 思路:
- 模块化设计
- 定义点数据结构。使用结构体定义点
- 定义计算两点间距离函数,
- 定义计算面积函数
#include <iostream>
#include<math.h>using namespace std;
#include<windows.h>/*设计一个三角形(Triangle)类,
构造函数初始化三个顶点,写一成员函数输出其面积。
写一成员函数绘制出该三角形。
在main()中测试这个类。*/typedef struct Point
{int x, y;
}Point;//先定义点类型, 用户保存三个点的位置
//函数求两点的距离
class Triangle
{private:Point a, b, c;// 像素计算, 像素是整数//int x1, y1, x2, y2, x3, y3;//分散参数public:Triangle(Point a, Point b, Point c);double Area(){//先求边长,在求面积double x = getDistance(a,b);double y = getDistance(b,c);double z = getDistance(a,c);double p = (x + y + z)/2;cout<<"边长 "<<x<<endl;cout<<"边长 "<<y<<endl;cout<<"边长 "<<z<<endl;//return sqrt((p*( p - x )*( p - y )*( p - z )));cout<<"三角形面积是 "<<p<<endl;return p;}double getDistance(Point b, Point a){double sum = sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y) * (a.y - b.y));return sum;}~Triangle(){// cout<<"Triangle 对象被-析构"<<endl;}
};
Triangle::Triangle(Point a, Point b, Point c)
{this->a = a;this->b = b;this->c = c;
};int main()
{Point p1;p1.x = 0;p1.y = 0;Point p2;p2.x = 0;p2.y = 3;Point p3;p3.x = 4;p3.y = 0;Triangle triangle(p1, p2, p3);triangle.Area();return 0;
}