21xrx.com
2025-03-21 23:11:17 Friday
文章检索 我的文章 写文章
C++程序:使用Point2D类计算p1、p2、p3之间的距离
2023-06-26 19:06:32 深夜i     12     0
C++ Point2D类 距离 p1 p2 p3

C++是一种高级编程语言,广泛应用于计算机编程和软件开发中。在C++编程中,Point2D类经常被使用。Point2D类通常用于表示二维平面中的一个点,其属性包括x坐标和y坐标。

在本文中,我们将介绍如何使用Point2D类计算三个点p1、p2和p3之间的距离。假设p1的坐标为(x1,y1),p2的坐标为(x2,y2),p3的坐标为(x3,y3),则它们之间的距离可以按照以下公式进行计算:

d1 = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))

d2 = sqrt((x3-x2)*(x3-x2) + (y3-y2)*(y3-y2))

d3 = sqrt((x3-x1)*(x3-x1) + (y3-y1)*(y3-y1))

其中,sqrt表示求平方根的函数。

我们可以使用Point2D类来表示这三个点的坐标。下面是一段可以计算三个点之间的距离的C++代码:

#include

#include

using namespace std;

class Point2D{

  private:

    double x;

    double y;

  public:

    Point2D(double x, double y)

      this->x = x;

      this->y = y;

    double getX()

      return this->x;

    double getY()

      return this->y;

};

int main(){

  Point2D p1(1,1);

  Point2D p2(2,2);

  Point2D p3(4,5);

  double d1, d2, d3;

  d1 = sqrt(pow(p2.getX()-p1.getX(),2) + pow(p2.getY()-p1.getY(),2));

  d2 = sqrt(pow(p3.getX()-p2.getX(),2) + pow(p3.getY()-p2.getY(),2));

  d3 = sqrt(pow(p3.getX()-p1.getX(),2) + pow(p3.getY()-p1.getY(),2));

  cout << "The distance between p1 and p2 is " << d1 << endl;

  cout << "The distance between p2 and p3 is " << d2 << endl;

  cout << "The distance between p1 and p3 is " << d3 << endl;

  return 0;

}

上述代码中,我们声明了一个Point2D类,其中包含了点的x和y坐标属性。在main函数中,我们定义了三个点p1、p2、p3,并分别计算了它们之间的距离。

这段代码的输出为:

The distance between p1 and p2 is 1.41421

The distance between p2 and p3 is 3.60555

The distance between p1 and p3 is 5.83095

通过这种方法,我们可以方便地使用Point2D类计算任意两个点之间的距离,并应用到我们需要的计算问题中。

  
  

评论区