直角坐标系多边形面积c++代码,在线等,急~~~~~~~~

来源:百度知道 编辑:UC知道 时间:2024/07/06 14:37:52
#include<iostream.h>
void main()
{
double X1,Y1,X2,Y2,X3,Y3;
double S=0;
cin>>X1>>Y1;
cin>>X2>>Y2;
while (cin>>X3>>Y3)
{
S+=X2*(Y3-Y1);
X1=X2;
Y1=Y2;
X2=X3;
Y2=Y3;
}
cout<<0.5*S;
}
上面是我自己写的,但有计算错误,数据是(375.12,120.51)(480.63, 257.45)(250.78,425.92)(175.72,210.83)根据公式S=0.5*∑X1*(Yi+1 - Yi-1)这是一个累加,从i=1,到n。非常急,求高手帮帮忙

(1)你源程序可读性和交互性都不太好,面积计算算法也有问题。我给你重写了一遍,详细见注释,你拿去运行一下吧:
(2)另外你的公式应该为:S=0.5*∑Xi*(Yi+1 - Yi-1) // 其中Xi由于你的笔误写成了X1

#include<iostream>
using namespace std;
struct POINT{ // 直角坐标系下的点结构
double x;
double y;
};
double PolygonArea(POINT* pVertex, int NUM){ // 计算多边形面积
double fArea = 0;
for(int i = 0; i < NUM - 1; i++){
fArea += (0.5 * (pVertex[i].x * pVertex[i + 1].y - pVertex[i].y * pVertex[i + 1].x));}
return fArea;
}
void main()
{
const int NUM = 4; // 要改变多边形的顶点数目,修改这个数字即可
POINT vertex[NUM]; // 多边形顶点数组
cout << "Please input " << NUM << " POINTS.\n";
// 从屏幕中获取多边形顶点数组,按提示输入即可
for(int i = 0; i < NUM; i++){
cout << "Please input POINT[" << i + 1 << "].x: ";
cin >> vertex[i].x;
cout << "Please input POINT[" << i + 1 << "].y: