main.cpp
#include <iostream> #include "header.h" using namespace std; int main() { CPoint X(2,5),Y(5,2),Z(7,8); CTriangle Tri1(X,Y,Z); cout<<"该三角形的周长为:"<<Tri1.perimeter()<<",面积为:"<<Tri1.area()<<endl<<endl; cout<<"该三角形"<<(Tri1.isRightTriangle()?"是":"不是")<<"直角三角形"<<endl; cout<<"该三角形"<<(Tri1.isIsoscelesTriangle()?"是":"不是")<<"等腰三角形"<<endl; return 0; }
header.cpp
#include <iostream> #include <cmath> #include "header.h" using namespace std; CPoint::CPoint(double xx,double yy) { x=xx; y=yy; } void CPoint::input() { char ch; cout<<"请输入坐标点(格式x,y ):"; while(1) { cin>>x>>ch>>y; if (ch==',') break; cout<<"输入的数据格式不符合规范,请重新输入\n"; } } void CPoint::output() { cout<<"("<<x<<", "<<y<<")"<<endl; } double CPoint::distance1(CPoint p) const { double d; d=sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y)); return d; } void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z) { A=X; B=Y; C=Z; } double CTriangle::perimeter(void) { double a=B.distance1(C),b=C.distance1(A),c=A.distance1(B); return (a + b + c); } double CTriangle::area(void) { double a=B.distance1(C),b=C.distance1(A),c=A.distance1(B); double s = (a + b + c) / 2; return sqrt(s * (s - a) * (s - b) * (s - c)); } bool CTriangle::isRightTriangle() { double a=B.distance1(C),b=C.distance1(A),c=A.distance1(B); double max=a; if(b>max) max=b; if(c>max) max=c; if(((max==a)&&(abs(a*a-b*b-c*c)<1e-7))||((max==b)&&(abs(b*b-a*a-c*c)<1e-7))||((max==c)&&(abs(c*c-b*b-a*a)<1e-7))) return true; else return false; } bool CTriangle::isIsoscelesTriangle() { double a=B.distance1(C),b=C.distance1(A),c=A.distance1(B); if((abs(a-b)<1e-7)||(abs(b-c)<1e-7)||(abs(c-a)<1e-7)) return true; else return false; }
header.h
#ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED class CPoint { private: double x; double y; public: CPoint(double xx=0,double yy=0); double distance1(CPoint p) const; void input(); void output(); }; 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(); private: CPoint A,B,C; }; #endif // HEADER_H_INCLUDED
运行结果:
学习心得:
好好学习 天天向上
原文地址:http://blog.csdn.net/ljd939952281/article/details/44902605