1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- #include <iostream>
- #include <cmath>
- #define pi 3.14
- using namespace std;
- class Circle {
- private:
- double radius; // 半径
- public:
- // 构造函数,初始化半径
- Circle(double r) : radius(r) {}
- // 重载的GetArea()成员函数,计算圆的面积
- double GetArea() const {
- return pi * radius * radius;
- }
- // 重载的GetArea()成员函数,计算圆环的面积
- double GetArea(double outerRadius) const {
- cout << "the ring is created!" << endl;
- return pi * (radius * radius - outerRadius * outerRadius);
- }
- };
- int main() {
- double radius;
- double outerRadius = 0; // 圆环的外半径,默认为0
- // 从用户输入读取半径
- cin >> radius;
- if (cin.fail()) {
- cerr << "Invalid input!" << endl;
- return 1;
- }
- // 创建Circle对象
- Circle circle(radius);
- cout << "the circle is created!" << endl;
- // 如果输入了两个值,则计算圆环面积
- if (cin.peek() != '\n') {
- cin >> outerRadius;
- Circle ring(outerRadius); // 创建圆环对象
- cout << "the ring's area is:" << circle.GetArea(outerRadius) << endl; //输出面积
- }
- else {
- cout << "the area is:" << circle.GetArea() << endl;
- }
- return 0;
- }
|