使用C++中类的方法定义一个圆类并求两圆的关系

C++定义一个圆类

题目:

定义一个圆类,包含圆心和半径,并创建两个圆,判断两圆是否相切、相交或相离。

预备知识

如何定义一个类

class 类名称
{

    //类内内容

};  //注意;不能省略

题目分析

根据题意首先定义一个点类,包含圆心坐标x,y两个成员变量和getdistance求两坐标距离的成员方法

class Point1
{
public:
	int x;   //圆心的横坐标
	int y;   //圆心的纵坐标

        //为圆心坐标赋值
	void setPoint1(int xx, int yy)
	{
		this->x = xx;
		this->y = yy;
	}

        //求两点间距离
	double getdistance(Point1 p)
	{
		int distance = pow(this->x - p.x, 2) + pow(this->y - p.y, 2);
		return pow(distance, 0.5);
	}
};

其次定义一个圆类,以点类为成员变量

class Circle
{
public:
	Point1 center;       //定义圆心
	int Radius;          //定义半径

	Circle(int xx ,int yy ,int r)
	{
		this->center.setPoint1(xx,yy);     //在圆类中使用点类的setPoint1方法定义圆心
		this->Radius = r;                  //为半径赋值
	}

        //比较两圆的关系
	void state(Circle p)
	{
		if (this->center.getdistance(p.center) == (this->Radius + p.Radius))
		{
			cout << "两圆相切" << endl;
		}
		else if (this->center.getdistance(p.center) >= (this->Radius + p.Radius))
		{
			cout << "两圆相离" << endl;
		}
		else
		{
			cout << "两圆相交" << endl;
		}
	}

};

完整代码如下

#include <iostream>
using namespace std;

class Point1
{
public:
	int x;
	int y;

	void setPoint1(int xx, int yy)
	{
		this->x = xx;
		this->y = yy;
	}

	double getdistance(Point1 p)
	{
		int distance = pow(this->x - p.x, 2) + pow(this->y - p.y, 2);
		return pow(distance, 0.5);
	}
};

class Circle
{
public:
	Point1 center;
	int Radius;

	Circle(int xx ,int yy ,int r)
	{
		this->center.setPoint1(xx,yy);
		this->Radius = r;
	}

	void state(Circle p)
	{
		if (this->center.getdistance(p.center) == (this->Radius + p.Radius))
		{
			cout << "两圆相切" << endl;
		}
		else if (this->center.getdistance(p.center) >= (this->Radius + p.Radius))
		{
			cout << "两圆相离" << endl;
		}
		else
		{
			cout << "两圆相交" << endl;
		}
	}

};

int main()
{
	Circle c1(0,0,1);
	Circle c2(0,2,1);
        Circle c3(0,1,1);
        Circle c4(9,9,1);

	c1.state(c2);   //相切
        c1.state(c3);   //相交
        c1.state(c4);   //相离

	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值