题目
依次输入一个二维多边形的顶点坐标,计算这些点围成的图形的周长和面积。
1.可以先输入一个数字表示顶点的个数
2.请附加足够多的注解,说明整个计算过程
3.编程规范,命名规范
4.如果跳过步骤1,直接输入坐标,那么如何让计算机理解现在可以停止输入,并开始计算了?
5.你能防止这些点的连线出现交叉吗?
程序
此程序基本达到5条要求,除最后一次相交可能外均被排除。因为最后一次相交的图形面积仍为正确值。
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <sstream> // std::istringstream
using namespace std;
int index = 0; // indicate whther 'end' is inputted
vector<double> X, Y; // contain the location of vertexes
// input numbers into a vector and test whether it is 'end'
vector<double> cinvec_d(std::string cin_d)
{
getline(cin, cin_d);
vector<double> vint;
if (cin_d == "end")
{
index = 1; // 'end' is inputted
return vint;
}
// change string into double
istringstream is(cin_d);
double i;
while (is >> i)
vint.push_back(i);
return vint;
}
// used to test whether there are crosses in sides
bool legal(double xi, double yi)
{
double epsilon = 1E-12; // allowing for precision in calculation
if (X.size() >= 3)
{
for (int i = 1; i != X.size() - 1; i++)
{
for (int j = 0; j != i; j++)
{
// define
double x1 = X[i], y1 = Y[i];
double x2 = X[j], y2 = Y[j];
double x3 = *(X.cend() - 1