C++判断一点是否在圆上(为了方便理解,以下分别用两种不同的方式实现)
1,创建两个不同的类
2,创建对象
3,通过对象调用方法判断是否在圆上
方法一、在头文件和源文件分别创建两个不同的类和函数方法。
提示:这种书写方式分别把函数的类和方法分开,整体阅读更加直观。
(1)创建一下两个头文件
在circle.h中写入:
#pragma once #include#include "point.h" using namespace std; class Circle { private: int m_R; point Center;//圆心 public: void setm_r(int r); int getm_r(); void set_center(point center); point get_center(); };
在point.h中写入:
#pragma once #includeusing namespace std; class point { private: int m_X; int m_Y; public: void setm_x(int x); int getm_x(); void setm_y(int y); int getm_y();//留住函数的声明 };
创建两个源文件
在circle.cpp中写入
#include "circle.h"
void Circle::setm_r(int r)
{
m_R = r;
}
int Circle::getm_r()
{
return m_R;
}
void Circle::set_center(point center)
{
Center = center;
}
point Circle::get_center()
{
return Center;
}
在point.cpp中写入:
#include "point.h"
void point::setm_x(int x)
{
m_X = x;
}
int point::getm_x()
{
return m_X;
}
void point::setm_y(int y)
{
m_Y = y;
}
int point::getm_y()
{
return m_Y;//留住函数的实现
}
测试代码:
#include方法二、传统方式:直接在一个源文件进行编译#include using namespace std; #include "circle.h" #include "point.h" void isinCircle(Circle& c, point& p) { int distance = (c.get_center().getm_x() - p.getm_x()) * (c.get_center().getm_x() - p.getm_x()) + (c.get_center().getm_y() - p.getm_y() * c.get_center().getm_y() - p.getm_y()); int R_distance = c.getm_r() * c.getm_r(); if (distance == R_distance) { cout << "在圆上" << endl; } else if (distance > R_distance) { cout << "在圆外" << endl; } else { cout << "在圆内" << endl; } } int main() { //创建圆 Circle C; C.setm_r(10); point p; p.setm_x(10); p.setm_y(0); C.set_center(p); //创建点 point p1; p1.setm_x(10); p1.setm_y(10); isinCircle(C, p1); system("pause"); return 0; }
代码如下:
#include#include using namespace std; class point { private: int m_X; int m_Y; public: void setm_x(int x) { m_X = x; } int getm_x() { return m_X; } void setm_y(int y) { m_Y = y; } int getm_y() { return m_Y; } }; class Circle { private: int m_R; point Center;//圆心 public: void setm_r(int r) { m_R = r; } int getm_r() { return m_R; } void set_center(point center) { Center = center; } point get_center() { return Center; } }; void isinCircle(Circle& c, point& p) { int distance = (c.get_center().getm_x() - p.getm_x()) * (c.get_center().getm_x() - p.getm_x()) + (c.get_center().getm_y() - p.getm_y() * c.get_center().getm_y() - p.getm_y()); int R_distance = c.getm_r() * c.getm_r(); if (distance == R_distance) { cout << "在圆上" << endl; } else if (distance > R_distance) { cout << "在圆外" << endl; } else { cout << "在圆内" << endl; } } int main() { //创建圆 Circle C; C.setm_r(10); point p; p.setm_x(10); p.setm_y(0); C.set_center(p); //创建点 point p1; p1.setm_x(10); p1.setm_y(10); isinCircle(C, p1); system("pause"); return 0; }



