C++编程定义一个Polygon类,包含属性:点坐标数组、点数等,和三个函数分别为:赋值、求多边形周长函数、求多边形面积函数,并在主函数中运行
时间: 2023-04-05 09:05:04 浏览: 60
好的,这是一个关于编程的问题,我可以回答。Polygon类可以定义如下:
```c++
class Polygon {
private:
int n; // 点数
vector<pair<double, double>> points; // 点坐标数组
public:
Polygon() : n(0) {}
Polygon(int n, vector<pair<double, double>> points) : n(n), points(points) {}
void setPoints(int n, vector<pair<double, double>> points) {
this->n = n;
this->points = points;
}
double getPerimeter() {
double perimeter = 0;
for (int i = 0; i < n; i++) {
int j = (i + 1) % n;
double dx = points[i].first - points[j].first;
double dy = points[i].second - points[j].second;
perimeter += sqrt(dx * dx + dy * dy);
}
return perimeter;
}
double getArea() {
double area = 0;
for (int i = 0; i < n; i++) {
int j = (i + 1) % n;
area += points[i].first * points[j].second - points[j].first * points[i].second;
}
return abs(area) / 2;
}
};
```
在主函数中可以这样使用:
```c++
int main() {
vector<pair<double, double>> points = {{0, 0}, {0, 1}, {1, 1}, {1, 0}};
Polygon polygon;
polygon.setPoints(4, points);
cout << "Perimeter: " << polygon.getPerimeter() << endl;
cout << "Area: " << polygon.getArea() << endl;
return 0;
}
```
输出结果为:
```
Perimeter: 4
Area: 1
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)