将任务4的解决用一个项目多个文件的方式实现,其中两个类的声明放在一个.h文件中,每个类的成员函数分别放一个文件,main()函数用一个文件。体会这样安排的优点。
//头文件 CTriangle.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(); //以(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(); //是否为等腰三角形
private:
CPoint A,B,C; //三顶点
};
//成员函数文件 CTriangle.cpp
#include<iostream>
#include"cmath"
#include"CTriangle.h"
using namespace std;
void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)
{
A = X;
B = Y;
C = Z;
}
//计算三角形的周长
double CTriangle::perimeter()
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
return a + b + c;
}
//计算并返回三角形的面积
double CTriangle::area(void)
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
double p = (a + b + c) / 2;
return sqrt ( p * ( p - a ) * ( p - b ) * ( p - c ) );
}
//是否为直角三角形
bool CTriangle::isRightTriangle()
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
if( abs(a * a + b * b - c * c < 1e-6) || abs(a * a + c * c - b * b < 1e-6) || abs(c * c + b * b - a * a < 1e-6) )
return true;
else
return false;
}
//是否为等腰三角
bool CTriangle::isIsoscelesTriangle()
{
double a = B.Distance(C), b = C.Distance(A), 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;
}
//两点间距离
CPoint::CPoint(double xx,double yy):x(xx),y(yy){}
double CPoint::Distance(CPoint p) const
{
return sqrt ( (p.x - x) * (p.x - x) + ( p.y - y ) * ( p.y - y ) ) ;
}
//输出
void CPoint::output()
{
cout << "(" << x << "," << y << ")" << endl;
}
//主函数文件 main.cpp
#include<iostream>
#include"CTriangle.h"
using namespace std;
void main()
{
CTriangle Tri1( CPoint(0,0),CPoint(1,1),CPoint(-1,1) );
cout << "该三角形周长:" << Tri1.perimeter() << "该三角形面积:" << Tri1.area() << endl;
cout << "该三角形" << (Tri1.isRightTriangle()? "是":"不是") << "直角三角形" << endl;
cout << "该三角形" << (Tri1.isIsoscelesTriangle()? "是":"不是" )<< "等腰三角形" << endl;
system("pause");
}