题目:分别输入两个圆的圆心坐标和半径,判断两个圆是否相交。
C实现:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
void IsIntersection(int x1, int y1, int r1, int x2, int y2, int r2) {
int d_r = r1 + r2;
int d_x = x1 - x2;
int d_y = y1 - y2;
int d_distance = sqrt(d_x*d_x + d_y*d_y);
if (d_distance > d_r) {
printf("两个圆不相交。\n");
}
else {
printf("两个圆相交。\n");
}
}
int main() {
int x1, y1, r1, x2, y2, r2;
printf("输入第一个圆的圆心坐标及半径:");
scanf("%d %d %d", &x1, &y1, &r1);
printf("输入第二个圆的圆心坐标及半径:");
scanf("%d %d %d", &x2, &y2, &r2);
IsIntersection(x1, y1, r1, x2, y2, r2);
return 0;
}
C运行结果:
C++实现:
#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 getDistance(Point &another) {
int d_x = m_x - another.m_x;
int d_y = m_y - another.m_y;
double distance = sqrt(d_x*d_x + d_y*d_y);
return distance;
}
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 IsIntersection(Circle &another) {
int d_r = m_r + another.m_r;
double d_distance = p.getDistance(another.p);
if (d_distance > d_r) {
return false;
}
else {
return true;
}
}
private:
int m_r;
Point p;
};
int main() {
int x, y, r;
Circle C1, C2;
cout << "输入第一个圆的圆心坐标:";
cin >> x >> y;
C1.setXY(x, y);
cout << "输入第一个圆的半径:";
cin >> r;
C1.setR(r);
cout << "输入第二个圆的圆心坐标:";
cin >> x >> y;
C2.setXY(x, y);
cout << "输入第二个圆的半径:";
cin >> r;
C2.setR(r);
bool flag = C1.IsIntersection(C2);
if (flag == true) {
cout << "两个圆相交" << endl;
}
else {
cout << "两个圆不相交" << endl;
}
return 0;
}
C++运行结果: