码迷,mamicode.com
首页 > 其他好文 > 详细

第12周上机实践项目4——点、圆的关系(2)

时间:2015-05-29 23:17:11      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:c++   cpp   数据   编程      

(5)在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试


代码

#include <iostream>
#include <cmath>
using namespace std;
class Point
{
protected:
    double x,y;
public:
    Point(double xx,double yy):x(xx),y(yy) {}
    double getx(){return x;}
    double gety(){return y;}
    friend ostream & operator<<(ostream &,const Point &);
};
ostream & operator<<(ostream &output,const Point &p)
{
    output<<"["<<p.x<<","<<p.y<<"]"<<endl;
    return output;
}
class Circle:public Point
{
protected:
    double r;
public:
    Circle(double xx,double yy,double rr):Point(xx,yy),r(rr) {}
    double getarea();
    friend ostream &operator<<(ostream &out,Circle &c);
    friend int locate(Point &p,Circle &c);

    bool operator>(Circle &c);
    bool operator<(Circle &c);
    bool operator==(Circle &c);
    bool operator>=(Circle &c);
    bool operator<=(Circle &c);
    bool operator!=(Circle &c);
};
double Circle::getarea()
{
    return 3.14*r*r;
}
ostream &operator<<(ostream &out,Circle &c)
{
    out<<"圆心=("<<c.getx()<<","<<c.gety()<<") 半径="<<c.r;
    return out;
}
int locate(Point &p,Circle &c)
{
    double x=p.getx()-c.getx(),y=p.gety()-c.gety(),s;
    s=sqrt(x*x+y*y);
    if(abs(s-c.r)<=0.00001)
        return 0;
    else if(s>c.r)
        return 1;
    else
        return -1;
}
bool Circle::operator>(Circle &c)
{
    return (this->r - c.r) > 0.000001;
}
bool Circle::operator<( Circle &c)
{
    return (c.r - this->r) > 0.000001;
}
bool Circle::operator>=( Circle &c)
{
    return !(*this < c);
}
bool Circle::operator<=( Circle &c)
{
    return !(*this > c);
}
bool Circle::operator==( Circle &c)
{
    return abs(this->r - c.r) < 1e-7;
}
bool Circle::operator!=( Circle &c)
{
    return abs(this->r - c.r) > 1e-7;
}
int main( )
{
    Circle c1(3,2,4),c2(4,5,5);      //c2应该大于c1
    Point p1(1,1),p2(3,-2),p3(7,3);  //分别位于c1内、上、外


    cout<<"圆c1: "<<c1<<endl;

    cout<<"点p1: "<<p1;
    cout<<"点p1在圆c1之"<<((locate(p1, c1)>0)?"外":((locate(p1, c1)<0)?"内":"上"))<<endl;

    cout<<"点p2: "<<p2;
    cout<<"点p2在圆c1之"<<((locate(p2, c1)>0)?"外":((locate(p2, c1)<0)?"内":"上"))<<endl;

    cout<<"点p3: "<<p3;
    cout<<"点p3在圆c1之"<<((locate(p3, c1)>0)?"外":((locate(p3, c1)<0)?"内":"上"))<<endl;

    cout<<"圆c1( "<<c1<<" )的面积是 "<<c1.getarea()<<endl;
    cout<<"圆c2( "<<c2<<" )的面积是 "<<c2.getarea()<<endl;
    cout<<"圆c1 ";
    if(c1>c2) cout<<"大于, ";
    if(c1<c2) cout<<"小于, ";
    if(c1>=c2) cout<<"大于等于, ";
    if(c1<=c2) cout<<"小于等于, ";
    if(c1==c2) cout<<"等于, ";
    if(c1!=c2) cout<<"不等于, ";
    cout<<"圆c2"<<endl;
    return 0;
}

运行结果:技术分享

第12周上机实践项目4——点、圆的关系(2)

标签:c++   cpp   数据   编程      

原文地址:http://blog.csdn.net/blue_skyrim/article/details/46239229

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!