练习:设计一个圆类(Circle),设计一个点类(Point),计算点和圆的关系。
解题思路:点和圆有三种关系,点在圆上、点在圆内、点在圆外。通过计算点和圆心的距离,对比半径来获得结果。
我的代码如下:
#include#include #include 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 #includeusing 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;
}



