gpt4 book ai didi

C++创建一个函数来获取两点之间的距离

转载 作者:行者123 更新时间:2023-11-27 23:56:49 27 4
gpt4 key购买 nike

在我的程序中,我创建了一个名为 Point 的构造函数,它有两个值。我还有一个 setgetscaletranslate 函数。我正在尝试创建一个函数来获取对象与另一点之间的距离。我遇到了麻烦,但任何帮助都会很棒。

#ifndef POINTMODEL
#define POINTMODEL
#define POINTDEB UG

#include <iostream>
#include <string.h>

using namespace std;

class Point {
public:
Point(void);
Point(double anX, double aY);
~Point();

void setPoint(double anX, double aY);

double getX();
double getY();

double scaleX(double theX);
double scaleY(double theY);
void translate(double theX, double theY);

void distance(const Point& aPoint);

protected:
private:
double theX;
double theY;
};

inline Point::Point(void)
{
theX = 1;
theY = 1;
cout << "\n The default constructor was called" << endl;
}

inline Point::Point(double anX, double aY)
{
cout << "\n regular constructor called";
}

inline Point::~Point()
{
cout << "\n the destructor was called" << endl;
}

inline void Point::setPoint(double anX, double aY)
{
theX = anX;
theY = aY;
}

inline double Point::getX()
{
return theX;
}

inline double Point::getY()
{
return theY;
}

inline double Point::scaleX(double theX)
{
return theX;
}

inline double Point::scaleY(double theY)
{
return theY;
}

inline void Point::translate(double offSetX, double offSetY)
{
cout << "X is translated by : " << offSetX << endl;
cout << "Y is translated by : " << offSetY << endl;
}

inline void Point::distance(const Point& aPoint)
{
}

#endif

Cpp文件:

#include "Point.h"

using namespace std;

int main(void)
{
cout << "\n main has started" << endl;

//Point myPoint;
Point myPoint(1, 1);

myPoint.setPoint(1, 1);

cout << "\n The value for X is : " << myPoint.getX() << endl;
cout << "\n The value for Y is : " << myPoint.getY() << endl;

cout << "\n X scaled by 2 is : " << myPoint.scaleX(2) << endl;
cout << "\n Y scaled by 2 is : " << myPoint.scaleY(2) << endl;

myPoint.translate(2, 3);

cout << "\n main has finished" << endl;

return 0;
}

最佳答案

您需要制作您的 Point::getX()Point::getY()函数 const像这样:

inline double Point::getX() const
{
return theX;
}

如果它们不是 const当参数是 const 时你不能调用它们引用。

那么距离是(将 return 从 void 更改为 double ):

double distance(const Point & aPoint) const
{
const double x_diff = getX() - aPoint.getX();
const double y_diff = getY() - aPoint.getY();
return std::sqrt(x_diff * x_diff + y_diff * y_diff);
}

我故意没用std::pow因为指数是2。您还需要包括 <cmath>对于 std::sqrt .

关于C++创建一个函数来获取两点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42088045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com