1. 设计立方体类
设计立方体类(Cube),求出立方体的面积( 2*a*b + 2*a*c + 2*b*c
)和体积( a * b * c
),分别用全局函数和成员函数判断两个立方体是否相等。
//立方体类
class Cub{
public:
void setL(int l){ mL = l; }
void setW(int w){ mW = w; }
void setH(int h){ mH = h; }
int getL(){ return mL; }
int getW(){ return mW; }
int getH(){ return mH; }
//立方体面积
int caculateS(){ return (mL*mW + mL*mH + mW*mH) * 2; }
//立方体体积
int caculateV(){ return mL * mW * mH; }
//成员方法
bool CubCompare(Cub& c){
if (getL() == c.getL() && getW() == c.getW() && getH() == c.getH()){
return true;
}
return false;
}
private:
int mL; //长
int mW; //宽
int mH; //高
};
//比较两个立方体是否相等
bool CubCompare(Cub& c1, Cub& c2){
if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH()){
return true;
}
return false;
}
void test(){
Cub c1, c2;
c1.setL(10);
c1.setW(20);
c1.setH(30);
c2.setL(20);
c2.setW(20);
c2.setH(30);
cout << "c1面积:" << c1.caculateS() << " 体积:" << c1.caculateV() << endl;
cout << "c2面积:" << c2.caculateS() << " 体积:" << c2.caculateV() << endl;
//比较两个立方体是否相等
if (CubCompare(c1, c2)){
cout << "c1和c2相等!" << endl;
}
else{
cout << "c1和c2不相等!" << endl;
}
if (c1.CubCompare(c2)){
cout << "c1和c2相等!" << endl;
}
else{
cout << "c1和c2不相等!" << endl;
}
}
2. 点和圆的关系
设计一个圆形类(AdvCircle),和一个点类(Point),计算点和圆的关系。
假如圆心坐标为x0, y0, 半径为r,点的坐标为x1, y1:
- 在圆上:(x1-x0)(x1-x0) + (y1-y0)(y1-y0) == r*r
- 点在圆内:(x1-x0)(x1-x0) + (y1-y0)(y1-y0) < r*r
- 点在圆外:(x1-x0)(x1-x0) + (y1-y0)(y1-y0) > r*r
//点类
class Point{
public:
void setX(int x){ mX = x; }
void setY(int y){ mY = y; }
int getX(){ return mX; }
int getY(){ return mY; }
private:
int mX;
int mY;
};
//圆类
class Circle{
public:
void setP(int x,int y){
mP.setX(x);
mP.setY(y);
}
void setR(int r){ mR = r; }
Point& getP(){ return mP; }
int getR(){ return mR; }
//判断点和圆的关系
void IsPointInCircle(Point& point){
int distance = (point.getX() - mP.getX()) * (point.getX() - mP.getX()) + (point.getY() - mP.getY()) * (point.getY() - mP.getY());
int radius = mR * mR;
if (distance < radius){
cout << "Point(" << point.getX() << "," << point.getY() << ")在圆内!" << endl;
}
else if (distance > radius){
cout << "Point(" << point.getX() << "," << point.getY() << ")在圆外!" << endl;
}
else{
cout << "Point(" << point.getX() << "," << point.getY() << ")在圆上!" << endl;
}
}
private:
Point mP; //圆心
int mR; //半径
};
void test(){
//实例化圆对象
Circle circle;
circle.setP(20, 20);
circle.setR(5);
//实例化点对象
Point point;
point.setX(25);
point.setY(20);
circle.IsPointInCircle(point);
}