#include <iostream> #include <cmath> class Circle { private: double radius; public: // Constructor Circle(double r) { radius = r; } // Mutator to set the radius void setRadius(double r) { radius = r; } // Accessor to get the radius double getRadius() const { return radius; } // Compute area double area() const { return M_PI * pow(radius, 2); } // Compute diameter double diameter() const { return 2 * radius; } // Compute circumference double circumference() const { return 2 * M_PI * radius; } }; int main() { double radius1, radius2; cout<<"Please input radius1:"<<endl; cin>>radius1; cout<<"Please input radius2:"<<endl; cin>>radius2; Circle c1(radius1); Circle c2(radius2); std::cout << "Circle 1: radius=" << c1.getRadius() << ", area=" << c1.area() << ", diameter=" << c1.diameter() << ", circumference=" << c1.circumference() << std::endl; c1.set_radius(radius1); c2.set_radius(radius2); std::cout << "Circle 2: radius=" << c2.getRadius() << ", area=" << c2.area() << ", diameter=" << c2.diameter() << ", circumference=" << c2.circumference() << std::endl; return 0; }为什么运行不出来
时间: 2023-07-14 13:14:05 浏览: 108
#include <iostream> #include<iomanip> using namespace std;九九乘法表
这段代码存在几个问题:
1.在类中定义了一个构造函数,但在主函数中没有使用这个构造函数来创建对象,而是直接使用了默认构造函数,应该改为使用构造函数来创建对象。
2.在类中定义了一个名为setRadius()的函数,但在主函数中却使用了一个名为set_radius()的函数,应该将其改为setRadius()。
以下是修改后的代码:
```
#include <iostream>
#include <cmath>
class Circle {
private:
double radius;
public:
// Constructor
Circle(double r) {
radius = r;
}
// Mutator to set the radius
void setRadius(double r) {
radius = r;
}
// Accessor to get the radius
double getRadius() const {
return radius;
}
// Compute area
double area() const {
return M_PI * pow(radius, 2);
}
// Compute diameter
double diameter() const {
return 2 * radius;
}
// Compute circumference
double circumference() const {
return 2 * M_PI * radius;
}
};
int main() {
double radius1, radius2;
std::cout<<"Please input radius1:"<<std::endl;
std::cin>>radius1;
std::cout<<"Please input radius2:"<<std::endl;
std::cin>>radius2;
Circle c1(radius1);
Circle c2(radius2);
std::cout << "Circle 1: radius=" << c1.getRadius()
<< ", area=" << c1.area()
<< ", diameter=" << c1.diameter()
<< ", circumference=" << c1.circumference() << std::endl;
c1.setRadius(radius1);
c2.setRadius(radius2);
std::cout << "Circle 2: radius=" << c2.getRadius()
<< ", area=" << c2.area()
<< ", diameter=" << c2.diameter()
<< ", circumference=" << c2.circumference() << std::endl;
return 0;
}
```
运行这段代码时,先输入radius1和radius2,然后程序会输出两个圆的半径、面积、直径和周长。
阅读全文