2016-03-03 130 views
-2

我在使用指針變量將點的座標更改爲(7,4)時遇到問題。我只是做了x = 7和y = 4,但我不認爲這是正確的。有人可以幫忙嗎?如何使用指針變量來更改值

我需要做的:

  • 的main()

    • 實例化一個Point對象和定義

    • 時初始化定義一個指針指向上面定義的對象

  • 使用指針變量

    • 更新的點的從原點

的座標(7,4)

  • 顯示的距離

    #include <iostream> 
    #include <math.h> 
    
    using namespace std; 
    
    class Point 
    { 
    private: 
        int x, y; 
    
    public: 
        Point(int x_coordinate, int y_coordinate); 
        int getVal(); 
        double distance(double x2, double y2); 
    }; 
    
    // Initialize the data members 
    
    Point::Point(int x_coordinate, int y_coordinate) 
    { 
        x = x_coordinate; 
        y = y_coordinate; 
    } 
    
    // Get the values of the data members. 
    
    int Point::getVal() 
    { 
        return x,y; 
    } 
    
    // Calculates and returns the point's distance from the origin. 
    
    double Point::distance(double x2, double y2) 
    { 
        double d; 
        d = sqrt(((x2 - 0)*(x2 - 0)) + ((y2 - 0) * (y2 - 0))); 
        return d; 
    } 
    
    //Allows user input and changes the point to (7,4) and displays the distance from origin. 
    
    int main() 
    { 
        int x,y; 
    
        cout << "Enter x coordinate followed by the y coordinate: " << endl; 
        cin >> x >> y; 
    
        Point p(x,y); 
    
        Point *newPointer = &p; 
    
        double theDistance = p.distance(x,y); 
    
        cout << "The point's distance from the origin is: " << theDistance << endl; 
    
        system("PAUSE"); 
    } 
    
  • +0

    'pointer-> member'。 –

    +0

    'return x,y;'意味着'返回y;' – MikeCAT

    +0

    @NickyC所以我需要創建一個新成員來改變數字? – TheEWL

    回答

    2

    要更新點的座標,你需要一個新的功能 -

    void Point::UpdateCoordinates(int x0, int y0) 
    { 
        x = x0; 
        y = y0; 
    } 
    

    對於距離(),我想你只需要在下面。

    double Point::distance() 
    { 
        return sqrt(x*x + y*y); 
    } 
    
    +0

    所以我需要將UpdateCoordinates中的值更改爲7和4? 我需要找到距離原點的距離,因此該公式中的x和y之一需要爲0. – TheEWL

    +0

    我沒有找到你,不應該使用sqrt(x * x + y * y)點(x,y)和(0,0)之間的距離?或者實際上你需要兩點之間的距離(原始和更新)? –

    +0

    @JianfengZhu原始問題提到「顯示距離原點的距離」。我認爲真正的問題是OP沒有關於變量或參數或東西等事物的明確概念。 –