C++ Bc. 12 cpp: Porovnání verzí
Bez shrnutí editace |
chyba ve výpočtu neuzavřeného polygonu (Bohumila Skřivanová, prosinec 2007) |
||
| (Není zobrazeno 7 mezilehlých verzí od 2 dalších uživatelů.) | |||
| Řádek 3: | Řádek 3: | ||
#include <algorithm> | #include <algorithm> | ||
#include <vector> | #include <vector> | ||
#include <cmath> | |||
struct Chyba | struct Chyba | ||
{ | { | ||
Chyba(std::string t) : text(t) {} | |||
std::string text; | std::string text; | ||
| Řádek 20: | Řádek 21: | ||
{ | { | ||
const int N = p.size(); | const int N = p.size(); | ||
if (N == 0) | |||
bool uzavreny = p[0].x == p[N-1].x | 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)) | if ((uzavreny && N <= 3) || (!uzavreny && N <= 2)) | ||
throw Chyba("polygon musi mit minimalne 3 vrcholy"); | throw Chyba("polygon musi mit minimalne 3 vrcholy"); | ||
double s = 0; | double s = 0; | ||
for (int i=0; i<N-1; i++) | for (int i=0; i<N-1; i++) | ||
s += (p[i+1].x - p[i].x)*(p[i+1].y + p[i].y); | 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); | return std::abs(s/2); | ||
| Řádek 56: | Řádek 59: | ||
} | } | ||
[ [[C | [ [[C++ Bc. 12|Zpět]] ] | ||
[[Kategorie:Programování]] | |||
[[Kategorie:C++]] | |||
Aktuální verze z 9. 12. 2006, 13:29
#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 ]