//案例:判断点和圆的位置关系
#include<iostream>
using namespace std;
//设计点类
class Point
{
public:
void setX(int x)
{
m_X = x;
}
int getX()
{
return m_X;
}
void setY(int y)
{
m_Y = y;
}
int getY()
{
return m_Y;
}
private:
int m_X;
int m_Y;
};
//设计圆类
class Circle
{
public:
void setR(int r)
{
m_R = r;
}
int getR()
{
return m_R;
}
void setCenter(Point center)
{
m_Center = center;
}
Point getCenter()
{
return m_Center;
}
private:
int m_R;
Point m_Center;
} ;
//判断点和圆的关系,比较点和圆心的距离和半径的长短
//两点之间的距离公式需要开根号,可以直接比较两条线段平方的大小
void isInCircle(Circle &c,Point &p)
{
//计算两点之间距离的平方
int distance =
(c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
(c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
//半径的平方
int rDistance = c.getR() * c.getR();
//判断,输出
if(distance == rDistance)
{
cout << "点在圆上" << endl;
}
else if(distance > rDistance)
{
cout << "点在圆外" << endl;
}
else if(distance < rDistance)
{
cout << "点在圆内" << endl;
}
}
int main()
{
//创建圆
Circle c;
c.setR(10);//设置圆半径
Point center;//设置圆心
center.setX(10);
center.setY(0);
c.setCenter(center);
//创建点
Point p;
p.setX(10);
p.setY(10);
//调用判断函数
isInCircle(c,p);
return 0;
}
|