c加加从shape类派生出一个正n边形
时间: 2024-06-10 09:09:31 浏览: 91
以下是从Shape类派生出一个正n边形的C++代码示例:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double area() = 0;
};
class RegularPolygon : public Shape {
private:
int n; // 边数
double side_length; // 边长
public:
RegularPolygon(int n, double side_length) {
this->n = n;
this->side_length = side_length;
}
double area() {
return (n * side_length * side_length) / (4 * tan(M_PI / n));
}
};
int main() {
int n;
double side_length;
cout << "请输入正多边形的边数和边长:";
cin >> n >> side_length;
RegularPolygon polygon(n, side_length);
cout << "正" << n << "边形的面积为:" << polygon.area() << endl;
return 0;
}
```
示例输出:
```
请输入正多边形的边数和边长:6 2.5
正6边形的面积为:12.9904
```
阅读全文