Új hozzászólás Aktív témák

  • sko

    csendes tag

    válasz KREE #3715 üzenetére

    KREE, a C++-ban (OOP-ban) való programozás egyik alaptulajdonsága, hogy nem jó a később majd megszépítjük módszer, már az alapokat is jól kell lerakni. A te feladatod központi problémája két pont távolságának kiszámítása. Először ezt kell C++-ban leprogramozni. Íme itt egy lehetséges implementáció. Remélem minden tiszta benne, ha nem kérdezz nyugodtan! Ha tiszta, akkor innen kell továbblépni a pontok konténerekbe tárolásával és távolságuk kiszámításával.

    #include <iostream>
    #include <cmath>

    using namespace std;

    class Point
    //If you need to calculate the distances of points, always start with creating a point object type.
    {
    int x = 0;
    int y = 0;

    public:

    Point(): x(0), y(0) {}
    Point(int X, int Y): x(X), y(Y) {}

    float operator - (const Point&);
    //Overloaded minus operator to calculate the distance of two points.
    //This will enormously simplify your work later.
    };

    float Point::operator - (const Point& other)
    {
    int X = x - other.x;
    int Y = y - other.y;
    //No abs() necessary, because we will square the coordinates anyway.
    float distance = sqrt(X*X + Y*Y);
    //Could be double, long double, whatever you like.
    return distance;
    //There is no real need for this variable, you could return the result of sqrt() directly. Whatever you like.
    }

    int main()
    {
    Point middlepoint(8,-6);
    Point endpoint(-5,10);

    float dist = middlepoint - endpoint;
    //Calculate the distance of these points. It's just that simple.
    cout << dist << endl;

    return 0;
    }

Új hozzászólás Aktív témák