C++-+ problem
-
Target: straight and many points are set on the plane. Find the points at a minimum and maximum distance from the straight. Code:
#include <iostream> #include <locale.h> #include <math.h> #include <conio.h> int Xn,Yn,Xk,Yk; float d,N; int x[i]; int y[i]; using namespace std;
int main ()
{setlocale(LC_ALL, "rus"); cout<<"Введите количество точек N - "; cin>>N; if (N<=0) { cout<<"Ошибка, количиство точек, это положительное число"<<endl<<"Введите количество точек - ";
cin>>N;
}
cout<<"Введите координаты прямой через пробел Xn, Yn, Xk, Yk"; cin>>Xn>>Yn>>Xk>>Yk;
for (i=1; i<N; i++)
cout<<"Введите координаты точек"; cin>>x[i];
cin>>y[i];
for (i=1; i<N; i++)
d[i]=((Yn-Yk)x[i]+(Xk-Xn)y[i]+((XnYk)-(XkYn)))/sqrt((pow(Xk-Xn),2)+(pow(Yk-Yn),2))
min=d[1];
max=d[1];
for (i=2; i<N; i++) {
if (d[i]<min)
min=d[i];
else {
if d[i]>max
max=d[i];
}
}
cout<<"Точка максимальна - "; cin>>max;
cout<<"Точка минимальна - "; cin>>min;
}
-
I'm sorry, I've got eyes on this code.
A more prudent solution is to provide a support structure
Point
and use standard algorithm to find a minimum element with its ownComparator'ом
♪In the code, this may look as follows:
#include <algorithm> #include <vector>
struct Point
{
Point(int x, int y): x(x), y(y) { }// Теоретически, может быть любой тип, который поддерживает // запись в кортеж (-,-), например, 'float'. int x, y;
};
struct PlaneDistancePointComparator
{
bool operator()(const Point& point1, const Point& point2)
{
// Необходимо сравнить точки в плане расстояния до
// соответствующей плоскости.
return Distance(point1, plane) < Distance(point2, plane);
}
};int main(int argc, char* argv[])
{
std::vector<Point> points;// Прочитать исходные точки и занести их в 'std::vector' с помощью // std::vector::push_back(Point(-,-)); const Point& minimalElement = *std::min_element(points.begin(), points.end(), PlaneDistancePointComparator()); const Point& maximalElement = *std::max_element(points.begin(), points.end(), PlaneDistancePointComparator()); // Получили 2 ссылки на структуры точек с минимальным и максимальным // расстоянием до плоскости.
}