用C++设计一个圆形类(Circle)和一个点类(Point),计算点在圆内部还是圆外部。
时间: 2024-02-21 22:57:27 浏览: 25
好的,我来为您提供C++的代码实现。
首先,我们需要定义一个圆形类(Circle)和一个点类(Point),其中圆形类需要包含圆心坐标和半径,点类需要包含横纵坐标。可以使用以下代码定义类:
```c++
class Circle {
private:
double x;
double y;
double r;
public:
Circle(double x, double y, double r) : x(x), y(y), r(r) {}
double getX() { return x; }
double getY() { return y; }
double getR() { return r; }
};
class Point {
private:
double x;
double y;
public:
Point(double x, double y) : x(x), y(y) {}
double getX() { return x; }
double getY() { return y; }
};
```
接下来,我们可以使用以下方法判断点是否在圆内:
```c++
bool is_inside(Circle circle, Point point) {
double distance = sqrt(pow(point.getX() - circle.getX(), 2) + pow(point.getY() - circle.getY(), 2));
if (distance < circle.getR()) {
return true;
} else {
return false;
}
}
```
其中,distance表示点到圆心的距离,如果距离小于半径,则点在圆内,返回true,否则返回false。
完整的代码如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
private:
double x;
double y;
double r;
public:
Circle(double x, double y, double r) : x(x), y(y), r(r) {}
double getX() { return x; }
double getY() { return y; }
double getR() { return r; }
};
class Point {
private:
double x;
double y;
public:
Point(double x, double y) : x(x), y(y) {}
double getX() { return x; }
double getY() { return y; }
};
bool is_inside(Circle circle, Point point) {
double distance = sqrt(pow(point.getX() - circle.getX(), 2) + pow(point.getY() - circle.getY(), 2));
if (distance < circle.getR()) {
return true;
} else {
return false;
}
}
int main() {
Circle circle(0, 0, 5);
Point point1(3, 4);
Point point2(6, 8);
if (is_inside(circle, point1)) {
cout << "Point 1 is inside the circle" << endl;
} else {
cout << "Point 1 is outside the circle" << endl;
}
if (is_inside(circle, point2)) {
cout << "Point 2 is inside the circle" << endl;
} else {
cout << "Point 2 is outside the circle" << endl;
}
return 0;
}
```
输出结果为:
```
Point 1 is inside the circle
Point 2 is outside the circle
```
希望我的回答能够帮助到您。