C++ 描述任意多边形的类及计算其面积和周长

该博客介绍了如何在C++中创建一个类来表示平面坐标系中的任意多边形,并能计算其面积和周长。虽然当前限制在第一象限,但提供了点和线的类,包含计算距离、直线方程、直线长度和相交判断等功能。文章还给出了使用示例,展示如何获取多边形的area和perimeter。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

这是一个可以在平面坐标系中表示任意多边形并且计算其面积和周长的类。不过目前只能在第一象限计算。使用时较简便,只要把多边形的各个顶点传进去就可以了(不用按顺序)

(其中面积的计算是参考https://blog.youkuaiyun.com/hemmingway/article/details/7814494的公式)

 

程序中附带包含了point 类,line 类。

      point 类:

               计算点点距离的函数:

double distancebetweenpoint(const point &a, const point &b);

 

               计算点到线距离的成员函数:

double distancetoline(const line &line)const;

 

 

       line 类:

               获得直线标准方程的函数:

void getStandardEquation(double &A, double &B, double &C)const;//get the standard equation of line( Ax+By+C=0)

 

               计算直线长度的成员函数:

 

double length()const;

               判断两条直线是否相交的成员函数:

              

bool line::iflinemeet(const line &other)const//return a bool value represent whether this line meets the other line (1 stand for yes, 0 for no)

 

 

 

(第一次用不是很会排版)

 

 

以下是使用样例:

	point a(3, 6), b(3, 3), c(0, 5),d(5,5),e(10,5),f(5,8),g(10,8);
	point v[4] = { e,f,g,d};
	polygon m(4, v);
	cout << "  area is " << m.area() << "  perimeter is " << m.perimeter()<<endl;

 

area(面积)和perimeter(周长)是double类型的。

 

 

 

以下是头文件中类的声明等等:

#pragma once
#include<iostream>
using namespace std;

#define PI 3.1415926535
enum errortype { noside,cantcalculate };//the type in exceptions class which may occured in shape's functions


class line;
class point;
class error;

//the exception class
class error {
private:
	errortype eor;
public:
	error(errortype e) :eor(e) {}//constructor
	const errortype what()const { return eor; }//for inquiry
};

//class point used to represent a point in a rectangular coordinate system
class point {
	friend double distancebetweenpoint
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值