C++第3讲:判断两个圆的关系 、构造和析构

这篇博客介绍了如何用C++编写代码来判断两个圆是否相交。首先定义了一个Point类用于表示点,包含设置坐标的方法和计算两点间距离的函数。接着定义了Circle类,包含设置半径和圆心坐标的方法,以及一个判断两个圆是否相交的函数,该函数通过计算两圆半径之和与圆心距离进行判断。在主函数中,用户输入两个圆的参数,程序输出它们是否相交。
摘要由CSDN通过智能技术生成

上一讲提到的判断两个圆的关系,通过类实现,看代码:

#include<iostream>
#include<cmath>

using namespace std;

//判断两个圆的关系
// 点类
class Point
{
public:
	void setXY(int x, int y)
	{
		m_x = x;
		m_y = y;
	}

	//计算两点间的方法
	double pointDistance(Point &another)
	{
		int d_x = m_x - another.m_x;
		int d_y = m_y - another.m_y;
		double dis = sqrt(d_x*d_x + d_y*d_y);
		return dis;
	}
private:
	int m_x;
	int m_y;

};

class Circle
{
public:
	void setR(int r)
	{
		m_r = r;
	}

	void setXY(int x, int y)
	{
		p0.setXY(x, y);
	}

	//判断是否相交
	bool isInter(Circle &another)
	{
		//两个半径只和
		int rr = m_r + another.m_r;
		//两圆心之间的距离
		double dis = p0.pointDistance(another.p0);
		if (dis <= rr)
		{
			//相交
			return true;
		}
		else
		{
			//不相交
			return false;
		}
	}
private:
	int m_r;
	Point p0;
};
int main(void)
{
	Circle c1, c2;
	int x, y, r;
	cout << "请输入第一个圆的半径" << endl;
	cin >> r;
	c1.setR(r);
	cout << "请输入第一个圆的x" << endl;
	cin >> x;
	cout << "请输入第一个圆的y" << endl;
	cin >> y;
	c1.setXY(x, y);


	cout << "请输入第二个圆的半径" << endl;
	cin >> r;
	c2.setR(r);
	cout << "请输入第二个圆的x" << endl;
	cin >> x;
	cout << "请输入第二个圆的y" << endl;
	cin >> y;
	c2.setXY(x, y);


	if (c1.isInter(c2) == true)
	{
		cout << "相交" << endl;
	}
	else
	{
		cout << "不相交" << endl;
	}


	system("pause");
	return 0;
}

首先新建一个point类

class Point
{
public:
	void setXY(int x, int y)
	{
		m_x = x;
		m_y = y;
	}

	//计算两点间的方法
	double pointDistance(Point &another)
	{
		int d_x = m_x - another.m_x;
		int d_y = m_y - another.m_y;
		double dis = sqrt(d_x*d_x + d_y*d_y);
		return dis;
	}
private:
	int m_x;
	int m_y;

};

设置两个私有成员变量
int m_x;
int m_y;
然后定义一个
void setXY(int x, int y)
{
m_x = x;
m_y = y;
}
为了方便操作和赋值
//计算两点间的方法
double pointDistance(Point &another)
{
int d_x = m_x - another.m_x;
int d_y = m_y - another.m_y;
double dis = sqrt(d_xd_x + d_yd_y);
return dis;
}
这里是计算两个点的距离,并返回,另外需要注意在,在同一类中两个对象可以互相调用。


这里又定义一个圆类
class Circle
{
public:
void setR(int r)
{
m_r = r;
}

void setXY(int x, int y)
{
	p0.setXY(x, y);
}

//判断是否相交
bool isInter(Circle &another)
{
	//两个半径只和
	int rr = m_r + another.m_r;
	//两圆心之间的距离
	double dis = p0.pointDistance(another.p0);
	if (dis <= rr)
	{
		//相交
		return true;
	}
	else
	{
		//不相交
		return false;
	}
}

private:
int m_r;
Point p0;
};
圆类中设置一个私有成员变量和一个私有类(也就是上面的点类,这样两个类之间就可以进行调用了)
这里设置了圆的半径设置函数
void setR(int r)
{
m_r = r;
}
void setXY(int x, int y)
{
p0.setXY(x, y);
}
设置点x,y,这里就是通过在circle类中的point成员变量,操作点类中的(x,y)
double dis = p0.pointDistance(another.p0);
if (dis <= rr)
{
//相交
return true;
}
else
{
//不相交
return false;
}
}
最后通过这个调用实现对判断
然后在主函数中进行这些函数的调用,参数设置,最后实现。
(完!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值