我在使用指针变量将点的坐标更改为(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 :(得分:2)
要更新点的坐标,您需要一个新函数 -
void Point::UpdateCoordinates(int x0, int y0)
{
x = x0;
y = y0;
}
对于距离(),我认为你只需要在下面。
double Point::distance()
{
return sqrt( x*x + y*y );
}