C++-----计算三角形面积

#include<iostream>
#include<cmath>
using namespace std;

class Point {  //坐标点类
public:
    const double x, y;
    Point(double x = 0.0, double y = 0.0) : x(x), y(y) {}
    //**********found**********
    double distanceTo(const Point& p  )const {   //到指定点的距离
        return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
    }
};

class Line {  //线段类
public:
    const Point p1, p2;  //线段的两个端点  

    //**********found**********
    Line(Point p1, Point p2) : p1(p1),p2(p2){}
    double length()const { return p1.distanceTo(p2); }  //线段的长度
};

class Triangle {   //三角形类
public:
    const Point p1, p2, p3;    //三角形的三个顶点

    //**********found**********
    Triangle(Point(p1),Point(p2),Point(p3)) : p1(p1), p2(p2), p3(p3) {}
    double length1()const { //边p1,p2的长度
        return Line(p1, p2).length();
    }
    double length2()const { //边p2,p3的长度
        return Line(p2, p3).length();
    }
    double length3()const { //边p3,p1的长度
        return Line(p3, p1).length();
    }
    double area()const {   //三角形面积
        //**********found**********
        double s = (length1()+length2() + length3())/2;
        return sqrt(s * (s - length1()) * (s - length2()) * (s - length3()));
    }
};

int main() {
    Triangle r(Point(0.0, 8.0), Point(5.0, 0.0), Point(0.0, 0.0));
    cout << "Side 1: " << r.length1() << endl;
    cout << "Side 2: " << r.length2() << endl;
    cout << "Side 3: " << r.length3() << endl;
    cout << "area: " << r.area() << endl;
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

navi’s electronic

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值