概述
编写 C++ 程序完成“圆形”以下功能:
- 定义一个
Point
类,其属性包括点的坐标,提供计算两点之间距离的方法,要求当用户不输入坐标数据时,能够默认为坐标原点 ( 0 , 0 ) (0,0) (0,0) - 定义一个圆形类,其属性包括圆心和半径
- 创建两个圆形对象,提示用户输入圆心坐标和半径,判断两个圆是否相交,并输出结果
分析
- 定义类
Point
,其中包含点的横坐标x
,纵坐标y
,以及计算两点之间距离的方法dis
- 定义类
Circle
,其中包含圆心p
,半径r
,以及判断两圆是否相交的方法judge
实现
#pragma once
class Point
{
public:
double x, y;
Point(double, double);
Point(); //默认的构造函数
~Point();
static double dis(Point, Point);
};
由于dis
函数只是求两点之间的距离,不会修改对象,因此声明为静态成员函数。
#pragma once
#include "point.h"
class Circle
{
public:
Point p;
double r;
Circle();
Circle(Point, double);
Circle(double, double, double);
~Circle();
static int judge(Circle, Circle);
};
同样,由于judge
函数只是判断两圆是否相交,也不会修改对象,因此声明为静态成员函数。
#include <cmath>
#include "point.h"
Point::Point()
{
x = y = 0;
}
Point::Point(double x0, double y0)
{
x = x0;
y = y0;
}
Point::~Point()
{}
double Point::dis(Point a, Point b)
{
return sqrt(pow((a.x - b.x), 2) + pow((a.y - b.y), 2));
}
#include <cmath>
#include "circle.h"
#include "point.h"
Circle::Circle(Point p0, double r0)
{
p = p0;
r = r0;
}
Circle::Circle(double x0, double y0, double r0)
{
p.x = x0;
p.y = y0;
r = r0;
}
Circle::Circle()
{
p.x = p.y = 0;
r = 1;
}
Circle::~Circle()
{}
int Circle::judge(Circle c1, Circle c2)
{
double dp = Point::dis(c1.p, c2.p);
if (dp > fabs(c1.r - c2.r) && dp < c1.r + c2.r)
return 1;
return 0;
}
#include <bits/stdc++.h>
#include "circle.h"
#include "point.h"
using namespace std;
int main()
{
Circle c1,c2;
cout << "第一个圆的圆心坐标和半径:" << endl;
cin >> c1.p.x >> c1.p.y >> c1.r;
cout << "第二个圆的圆心坐标和半径:" << endl;
cin >> c2.p.x >> c2.p.y >> c2.r;
cout << "第一个圆的坐标为" << '(' << c1.p.x << ',' << c1.p.y << ")," << "半径为" << c1.r << endl;
cout << "第二个圆的坐标为" << '(' << c2.p.x << ',' << c2.p.y << ")," << "半径为" << c2.r << endl;
cout << "两圆圆心距离为" << Point::dis(c1.p, c2.p) << endl;
if (Circle::judge(c1, c2))
cout << "两圆相交" << endl;
else
cout << "两圆不相交" << endl;
return 0;
}