C++ Bc. 12 cpp
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <cmath>
struct Chyba
{
Chyba(std::string t) : text(t) {}
std::string text;
};
struct Bod {
double x, y;
};
typedef std::vector<Bod> Polygon;
double plocha(const Polygon& p)
{
const int N = p.size();
if (N == 0)
throw Chyba("polygon musi mit minimalne 3 vrcholy");
bool uzavreny = p[0].x == p[N-1].x && p[0].y == p[N-1].y;
if ((uzavreny && N <= 3) || (!uzavreny && N <= 2))
throw Chyba("polygon musi mit minimalne 3 vrcholy");
double s = 0;
for (int i=0; i<N-1; i++)
s += (p[i+1].x - p[i].x)*(p[i+1].y + p[i].y);
if (!uzavreny)
s += (p[0].x - p[N-1].x)*(p[0].y + p[N-1].y);
return std::abs(s/2);
}
int main()
{
using namespace std;
Polygon p;
istringstream input("1 1 0 2 -1 1 -1 -1 1 -1");
Bod b;
while (input >> b.x >> b.y) p.push_back(b);
try
{
cout << "Plocha = " << plocha(p);
}
catch(Chyba &ch)
{
cout << ch.text << endl;
}
}
[ Zpět ]