【学习笔记】C++类和对象练习——计算和圆的关系

练习:设计一个圆类(Circle),设计一个点类(Point),计算点和圆的关系。


解题思路:点和圆有三种关系,点在圆上、点在圆内、点在圆外。通过计算点和圆心的距离,对比半径来获得结果。

我的代码如下:

#include<iostream>
#include<string>
#include<math.h>

using namespace std;

// 设计的点类
class Point
{

public:
	void setX(int x)
	{
		this->x = x;
	}
	int getX()
	{
		return this->x;
	}

	void setY(int y)
	{
		this->y = y;
	}
	int getY()
	{
		return this->y;
	}

private:
	int x;
	int y;
};

// 设计的圆类
class Circle
{
public:
	void setM_R(int m_r)
	{
		this->m_r = m_r;
	}
	int getM_R()
	{
		return this->m_r;
	}

	void setCX(int cx)
	{
		this->cx = cx;
	}
	int getCX()
	{
		return this->cx;
	}

	void setCY(int cy)
	{
		this->cy = cy;
	}
	int getCY()
	{
		return this->cy;
	}

	// 用于计算点和圆的关系
	string calculateDistance(Point &p)
	{
		int x_p = p.getX();
		int y_p = p.getY();
		int x_c = cx;
		int y_c = cy;
        // 这里使用了sqrt函数计算开方。计算平方时第一次错误的使用了^2.
		double distance = sqrt((x_c - x_p)*(x_c - x_p) + (y_c - y_p)*(y_c - y_p));
		cout << distance << endl;
		if (distance > m_r)
		{
			return "点在圆外";
		}
		else if (distance == m_r)
		{
			return "点在圆上";
		}
		else
		{
			return "点在圆内";
		}
	}

private:
	int m_r;
	int cx;
	int cy;
};

int main()
{

	Point p1;
	Point p2;
	Point p3;

	p1.setX(1);
	p1.setY(2);

	p2.setX(4);
	p2.setY(2);

	p3.setX(1);
	p3.setY(4);

	Circle c1;
	c1.setCX(3);
	c1.setCY(2);
	c1.setM_R(2);

	cout << "p1和圆的关系是:" <<
		c1.calculateDistance(p1) << endl;
	cout << "p2和圆的关系是:" <<
		c1.calculateDistance(p2) << endl;
	cout << "p3和圆的关系是:" <<
		c1.calculateDistance(p3) << endl;

	system("pause");

	return 0;
}

练习总结:

不足改进:

1、老师的思路,既然设计出了“点”类,可以直接使用该类设计圆心。

void setCenter(Point center)
{
    m_Center = center;
}

2、为了提高代码的可读性,将类单独使用类.h和类.cpp文件。

以Point类为例,point.h头文件中内容为:

#pragma once
#include<iostream>
using namespace std;


class Point
{

public:
	void setX(int x);

	int getX();

	void setY(int y);

	int getY();

private:
	int x;
	int y;
};

point.cpp文件内容为:

#include "point.h"

void Point::setX(int x)
{
	this->x = x;
}
int Point::getX()
{
	return this->x;
}

void Point::setY(int y)
{
	this->y = y;
}
int Point::getY()
{
	return this->y;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值