源程序:
//main.cpp #include<iostream> #include "class.h" #include<cmath> using namespace std; void main() { CPoint p1, p2, p3; CTriangle tri(p1, p2, p3); double b1, b2, b3; while(1) { p1.input(); p2.input(); p3.input(); tri.setTriangle(p1, p2, p3); b1 = tri.geta(); b2 = tri.getb(); b3 = tri.getd(); if((b1 + b2) > b3 && (b2 + b3) && (b1 + b3) > b2) { break; } else { cout << "输入三点的坐标无法构成三角形,请重新输入!!!" <<endl; } } cout << "三角形的周长为:" << tri.perimeter() << endl; cout << "三角形的面积为:" << tri.area() << endl; cout << "该三角形" << (tri.isRightTriangle()?"是":"不是") << "直角三角形" << endl; cout << "该三角形" << (tri.isIsoscelesTriangle()?"是":"不是") << "等腰三角形" << endl; } //class.h class CPoint { private: mutable double x; // 横坐标 mutable double y; // 纵坐标 public: CPoint(double xx=0,double yy=0); double Distance(CPoint p); void input(); //以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);//取三角形三边长度 double perimeter(void);//计算三角形的周长 double area(void);//计算并返回三角形的面积 bool isRightTriangle(); //是否为直角三角形 bool isIsoscelesTriangle(); //是否为等腰三角形 double geta(); double getb(); double getd(); private: CPoint A,B,C; //三顶点 double a, b, c; }; //CTriangle.cpp #include<iostream> #include "class.h" #include<cmath> using namespace std; void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)//取三角形三边长度 { A = X; B = Y; C = Z; a = B.Distance(C); b = C.Distance(A); c = A.Distance(B); } double CTriangle::geta() { return a; } double CTriangle::getb() { return b; } double CTriangle::getd() { return c; } double CTriangle::perimeter(void)//计算三角形的周长 { return a + b + c; } double CTriangle::area(void)//计算并返回三角形的面积 { double p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); } bool CTriangle::isRightTriangle() { if(abs(a * a - b * b - c * c) < 1e-6 || abs(b * b - a * a - c * c) < 1e-6 || abs(c * c - a * a - b * b) < 1e-6 ) { return true; } else { return false; } } bool CTriangle::isIsoscelesTriangle() { if(abs(a - b) < 1e-6 || abs(a - c) < 1e-6 || abs(b - c) < 1e-6 ) { return true; } else { return false; } } CPoint::CPoint(double xx, double yy) { x = xx; y = yy; } double CPoint::Distance(CPoint p) { return(sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y))); } void CPoint::input() { char z; while(1) { cout << "请以 x , y 形式输入坐标点:"; cin >> x >> z >> y; if(z == ',') { break; } else { cout<< "输入格式有误!!!" << endl; } } }