头文件类,名字c.h
class CPoint
{private:
double x; // 横坐标
double y; // 纵坐标
public:
CPoint(double xx=0,double yy=0);
double Distance(CPoint p) const; // 两点之间的距离(一点是当前点,另一点为参数p)
void input(); //以x,y 形式输入坐标点
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; //三顶点
};
头文件函数的定义,名字cw.h
#include <iostream>
#include "c.h"
#include <Cmath>
using namespace std;
CPoint::CPoint(double xx,double yy)
{
x = xx;
y = yy;
}
// 两点之间的距离(一点是当前点,另一点为参数p)
double CPoint::Distance(CPoint p) const
{
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
//以x,y 形式输入坐标点
void CPoint::input()
{
while(1)
{
char c;
cin>>x>>c>>y;
if(c != ',')
{
cout<<"格式错误!重输入!";
}
else
break;
}
}
//以(x,y) 形式输出坐标点
void CPoint::output()
{
cout<<"("<<x<<", "<<y<<")"<<endl;
}
void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)//
{
A = X;
B = Y;
C = Z;
}
//计算三角形的周长
double CTriangle::perimeter(void)
{
double a = B.Distance(C),b = A.Distance(C),c = A.Distance(B);
return (a + b + c);
}
//计算并返回三角形的面积
double CTriangle::area(void)
{
double s;
double a = B.Distance(C),b = A.Distance(C),c = A.Distance(B);
s = (a + b + c) /2;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
//是否为直角三角形
bool CTriangle::isRightTriangle()
{
double a = B.Distance(C),b = A.Distance(C),c = A.Distance(B);
if(abs(a*a+b*b-c*c) < 1e-6 ||abs(b*b+c*c-a*a) < 1e-6 || abs(a*a+c*c-b*b) < 1e-6)
{
return true;
}
else
{
return false;
}
}
//是否为等腰三角形
bool CTriangle::isIsoscelesTriangle()
{
double a = B.Distance(C),b = A.Distance(C),c = A.Distance(B);
if(abs(a-b) < 1e-6 || abs(a-c) < 1e-6 || abs(b-c) < 1e-6)
{
return true;
}
else
{
return false;
}
}
主函数,文件名main.cpp
#include <iostream>
#include "cw.h"
using namespace std;
void main(void)
{
CTriangle Tri1(CPoint(0,2),CPoint(2,0),CPoint(0,0)); //定义三角形类的一个实例(对象)
cout<<"该三角形的周长为:"<<Tri1.perimeter()<<",面积为:"<<Tri1.area()<<endl<<endl;
cout<<"该三角形"<<(Tri1.isRightTriangle()?"是":"不是")<<"直角三角形"<<endl;
cout<<"该三角形"<<(Tri1.isIsoscelesTriangle()?"是":"不是")<<"等腰三角形"<<endl;
system("pause");
}
感言:思路清晰,容易找错!