将项目2用“一个项目多个文件”的方式实现,其中两个类的声明放在同一个.h文件中,每个类的成员函数分别放一个文件,main()函数用一个文件。体会这样安排的优点。
main 函数:
#include <iostream>
#include <cmath>
#include "need.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;
}
头文件 need.h 建立#ifndef NEED_H_INCLUDED
#define NEED_H_INCLUDED
class CPoint
{
private:
double x; // 横坐标
double y; // 纵坐标
public:
CPoint(double xx=0,double yy=0);
double Distance1(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)
{
a=B.Distance1(C),b=C.Distance1(A),c=A.Distance1(B); //给出三点的构造函数
}
void setTriangle(CPoint &X,CPoint &Y,CPoint &Z);//
float perimeter(void);//计算三角形的周长
float area(void);//计算并返回三角形的面积
bool isRightTriangle(); //是否为直角三角形
bool isIsoscelesTriangle(); //是否为等腰三角形
private:
CPoint A,B,C; //三顶点
double a,b,c; //三角形三条边
};
#endif // NEED_H_INCLUDED
#include <iostream>
#include <cmath>
#include "need.h"
using namespace std;
CPoint::CPoint(double xx,double yy)
{
x=xx;
y=yy;
}
double CPoint::Distance1(CPoint p) const //两点之间的距离(一点是当前点——想到this了吗?,另一点为p)
{
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
void CPoint::input() //以x,y 形式输入坐标点
{
char ch;
cout<<"请输入坐标点(格式x,y ):";
while(1)
{
cin>>x>>ch>>y;
if (ch==',') break;
cout<<"输入的数据格式不符合规范,请重新输入\n";
}
}
void CPoint::output() //以(x,y) 形式输出坐标点
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
#include <iostream>
#include <cmath>
#include "need.h"
using namespace std;
void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)//
{
A=X;
B=Y;
C=Z;
a=B.Distance1(C),b=C.Distance1(A),c=A.Distance1(B);
}
float CTriangle::perimeter(void)//计算三角形的周长
{
return (a + b + c);
}
float CTriangle::area(void)//计算并返回三角形的面积
{
double q=(a + b + c)/2;
return sqrt(q*(q-a)*(q-b)*(q-c));
}
bool CTriangle::isRightTriangle() //是否为直角三角形
{
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() //是否为等腰三角形
{
if((abs(a-b)<1e-7)||(abs(b-c)<1e-7)||(abs(c-a)<1e-7)) //double 型数据不可直接比较大小
return true;
else
return false;
}
原文地址:http://blog.csdn.net/wh201458501106/article/details/44936279