是一个circle类程序
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/15 15:00:50
是一个circle类程序
是一个circle类程序
是一个circle类程序
根据题意实现代码如下:
#include <iostream>#include <cmath>
#include <string>
using namespace std;
const double PI = 3.14159265358979323846;
class Circle{
public:
Circle():x(0),y(0),r(1){};
Circle(double ix, double iy, double ir):x(ix), y(iy), r(ir){};
double area(){return PI*r*r;}
double perimeter(){return 2*PI*r;}
int relation(Circle &c);
void show();
private:
double x, y, r;
};
int Circle::relation(Circle &c){
double d = sqrt((x - c.x) * (x - c.x) + (y - c.y) * (y - c.y));
if(d > r + c.r)
return -1;
else if(d == r + c.r || d == fabs(r-c.r))
return 1; //相切
else if(d < r + c.r && d > fabs(r - c.r))
return 2; //相交
else
return 3;
}
void Circle::show(){
cout << "圆心为(" << x << ", " << y << "),半径为" << r;
}
class TestCircle{
public:
void run();
void AddCircle(Circle c, int i){p[i] = c;}
private:
Circle p[2];
void testRelation(Circle &m, Circle &n);
void testArea(Circle &c);
void testPerimeter(Circle &c);
};
void TestCircle::run(){
testArea(p[0]);
testPerimeter(p[0]);
testArea(p[1]);
testPerimeter(p[1]);
testRelation(p[0],p[1]);
}
void TestCircle::testRelation(Circle &m, Circle &n){
int s = m.relation(n);
string t = "相离";
if(s == 1){
t = "相切";
}
else if(s == 2){
t = "相交";
}
else if(s == 3){
t = "相容";
}
m.show();
cout << "和";
n.show();
cout << ",两圆" << t << endl;
}
void TestCircle::testArea(Circle &c){
c.show();
cout << ",该圆面积为:" << c.area() << endl;
}
void TestCircle::testPerimeter(Circle &c){
c.show();
cout << ",该圆周长为:" << c.perimeter() << endl;
}
int main(){
double x,y,r;
TestCircle test;
cout << "please input x y r of circle 1:" << endl;
cin >> x >> y >> r;
test.AddCircle(Circle(x,y,r), 0);
cout << "please input x y r of circle 2:" << endl;
cin >> x >> y >> r;
test.AddCircle(Circle(x,y,r), 1);
test.run();
return 0;
}
如果感觉还行,还请尽快采纳.