【问题标题】:Area of a triangle in a cartesian plane笛卡尔平面中三角形的面积
【发布时间】:2016-11-19 11:23:40
【问题描述】:

我正在尝试制作一个程序,让用户输入 a 对 xy 坐标。程序必须使用距 (0,0) 最远的三个点作为三角形的顶点。程序必须输出三角形的面积。我知道它的公式,但我无法从 (0,0) 获得最远的三个点。

这里我的代码只对 x 坐标进行升序排序。如何对对进行排序并获得最远的三个点? 或者有没有更好的方法来制作这个程序?

int main() {
    int x, a, b, t;
    cin >> a; // a pairs of x and y
    int xcoor[a], ycoor[a];
    for (x = 1; x <= a; x++)
    {
        //enter coordinates
        cin >> xcoor[x] >> ycoor[x];
    }
    for (x = 0; x < a; x++)
    {
        for (int y = 0; y < a - 1; y++)
        {
            if (xcoor[y] > xcoor[y + 1])
            {
                t = xcoor[y];
                xcoor[y] = xcoor[y + 1];
                xcoor[y + 1] = t;
            }
        }
    }
    return 0;
}

【问题讨论】:

    标签: c++ sorting cartesian


    【解决方案1】:

    一种方法是找到这些点的convex hull,最远的点是那个凸包的顶点,取最远的3个顶点。

    This 是找到一组点的凸包的一种方法。

    您也可以查看this,它可能会帮助您找到解决问题的方法。

    【讨论】:

      【解决方案2】:

      您可以定义一个 struct Point 来定义一个坐标,而不是使用两个单独的变量。

      使用operator&lt; 表示与中心的距离,您可以使用std::sortPoint 的数组/向量进行排序。

      类似:

      struct Point {
        int x, y;
      
        bool operator<(const Point& src) const
          { return x*x + y*y < src.x*src.x + src.y*src.y; // or anything else
          }
      };
      
      int main() {
          int x,a,b,t;
          cin>>a; // a pairs of x and y
          Point point[a]; // be careful, it is a gcc extension since a is not a compilation constant
          for (x=0; x<a; x++) // be careful, arrays in C/C++ starts from 0!
          {
          //enter coordinates
          cin>>point[x].x>>point[x].y;
          }
          std::sort(&point[0], &point[a]);
          return 0;
      }
      

      帮助您找到最远的三个点。

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多