第六周实验报告4

来源:互联网 发布:网络编程入门书籍 编辑:程序博客网 时间:2024/05/17 03:53

实验目的:设计一个三角形类,能够输入三角形的三个顶点,求出其面积、周长,并判断其是否为直角三角形和等腰三角形
1.这二个问题需要用到两个类,顶点类和三角形类  2.关于三边的处理可以增加三个似有属性,在初始化是求出来备用,也可以在需要时计算得到

实验代码:

#include <iostream>#include <cmath>using namespace std;class CPoint{private:    double x;    double y;public:    double Distance(CPoint p) const; //两点之间的距离    void input(); //以x,y形式输入坐标点    void output(); //以(x, y)形式输出坐标点};class CTriangle{public:    CTriangle(CPoint &X, CPoint &Y, CPoint &Z):A(X), B(Y), C(Z){} //给出三个点的构造函数    void setTriangle(CPoint &X, CPoint &Y, CPoint &Z); //    float perimter(void); //计算三角形的周长    float area(void); //计算并返回三角形的面积    bool isRightTriangle(); //是否为直角三角形    bool isTsoscelesTrangle(); //是否为等腰三角形private:    CPoint A, B, C; //三顶点};void main(){    CPoint p1, p2, p3;    cout << "请输入三角形三个顶点的坐标: " << endl;    p1.input();    p2.input();    p3.input();    p1.output();    p2.output();    p3.output();    CTriangle c(p1, p2, p3);    cout << endl << "构成三角形的周长为: " << c.perimter() << "; " << "面积为: " << c.area() << endl;;    cout << "此三角形" << (c.isRightTriangle()?"是":"不是") << "直角三角形" << ";";    cout << (c.isTsoscelesTrangle()?"是":"不是") << "等腰三角形" << endl;    system("pause");}void CPoint::input(){    double x1, y1;    cin >> x1 >> y1;    x = x1;    y = y1;}void CPoint::output(){    cout << "(" << x << ", " << y << ")";}double CPoint::Distance(CPoint p) const //两点之间的距离{    double s = sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));    return s;}float CTriangle::perimter(void) //计算三角形的周长{    double S = A.Distance(B) + B.Distance(C) + A.Distance(C);    return S;}float CTriangle::area(void) //计算三角形的面积{    double a = A.Distance(B);    double b = B.Distance(C);    double c = A.Distance(C);    double p = (a + b + c) / 2;    double Area = sqrt(p * (p - a) * (p - b) * (p - c));        return Area;}bool CTriangle::isRightTriangle() //是否为直角三角形{    double a = A.Distance(B);    double b = B.Distance(C);    double c = A.Distance(C);    double a1 = a * a;    double b1 = b * b;    double c1 = c * c;    if(a1 + b1 == c1 || a1 + c1 == b1 || b1 + c1 == a1) return true;    elsereturn false;}bool CTriangle::isTsoscelesTrangle() //是否为等腰三角形{    double a = A.Distance(B);    double b = B.Distance(C);    double c = A.Distance(C);    if(a == b || a == c || b == c)return true;    elsereturn false;}


实验结果截图:


实验心得:

嗯,挺难的,因为用到了两个类,而且还有两个类之间值的传递,好就好在在任务三中,一些问题已经解除了,困难就在定义三边的类中,特别是:CTriangle(CPoint &X, CPoint &Y, CPoint &Z):A(X), B(Y), C(Z){} //给出三个点的构造函数,真的是纠结了我很久,老长一段时间都不知道该怎么下手,弄不清(CPoint &X, CPoint &Y, CPoint &Z)的值到底是怎么传递的,其他的都还好,没什么难的啦,因为以前的实验中,像是求三角形的周长和面积的问题都已经碰到过了,所以,一些不清楚的问题搞清楚了,其他一些函数就都能迎刃而解。