面向对象——案例练习(5)判断两个圆是否相交
多个文件实现:
//Mypoint.h #pragma once class Mypoint { public: void setXY(int x, int y); double disPoint(Mypoint &another); private: int m_x; int m_y; };
//Mypoint.cpp #include "Mypoint.h" #include "cmath" void Mypoint::setXY(int x, int y) { m_x = x; m_y = y; } double Mypoint::disPoint(Mypoint &another) { return sqrt((m_x - another.m_x)*(m_x - another.m_x) + (m_y - another.m_y)*(m_y - another.m_y)); }
//Mycircle.h #pragma once #include "Mypoint.h" class Mycircle { public: void setR(int r); void setXY(int x, int y); bool isIntersect(Mycircle &another); private: int m_r; Mypoint p; };
//Mycircle.cpp #include "Mycircle.h" void Mycircle::setR(int r) { m_r = r; } void Mycircle::setXY(int x,int y) { p.setXY(x, y); } bool Mycircle::isIntersect(Mycircle &another) { double dis = p.disPoint(another.p); int rr = m_r + another.m_r; if (dis <= rr) { return true; } else { return false; } }
//main.cpp #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "Mycircle.h" #include "Mypoint.h" using namespace std; int main(void) { Mycircle c1,c2; int x,y,r; cout << "圆1的半径:" << endl; cin >> r; c1.setR(r); cout << "圆1的x:" << endl; cin >> x; cout << "圆1的y:" << endl; cin >> y; c1.setXY(x, y); cout << "圆2的半径:" << endl; cin >> r; c2.setR(r); cout << "圆1的x:" << endl; cin >> x; cout << "圆1的y:" << endl; cin >> y; c2.setXY(x, x); if(c1.isIntersect(c2)==true) { cout << "相交" << endl; } else { cout << "不相交" << endl; } return 0; }
一个文件实现:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "cmath" using namespace std; class Point { public: void setXY(int x, int y) { m_x = x; m_y = y; } double disPoint(Point &another) { return sqrt((m_x- another.m_x)*(m_x - another.m_x)+ (m_y - another.m_y)*(m_y - another.m_y)); } private: int m_x; int m_y; }; class Circle { public: void setR(int r) { m_r = r; } void setXY(int x, int y) { p.setXY(x, y); } //判断圆是否与我相交 bool isInteract(Circle &another) { int rr = m_r + another.m_r; double dis = p.disPoint(another.p); if (rr >= dis) return true; else return false; } private: int m_r; Point p; }; int main(void) { Circle c1, c2; int x, y, r; cout << "圆一的半径:"; cin >> r ; c1.setR(r); cout << "圆一的x:"; cin >> x; cout << "圆一的y:"; cin >> y; c1.setXY(x, y); cout << "圆二的半径:"; cin >> r; c2.setR(r); cout << "圆二的x:"; cin >> x; cout << "圆二的y:"; cin >> y; c2.setXY(x, y); if (c1.isInteract(c2) == true) cout << "相交" << endl; else cout << "不相交" << endl; return 0; }