【问题标题】:Finding minimum and maximum points coordinates with C++使用 C++ 查找最小和最大点坐标
【发布时间】:2013-10-22 23:45:32
【问题描述】:

我有一个包含点的 X、Y、Z 坐标的文本文件。我的目标是找到最小和最大点并将其写入另一个文件。为此,我编写了一个距离函数。具有最大距离的点是最小点和最大点。这是我的代码。它可以工作,但它不会计算或写入任何东西。

#include <iostream>
#include<fstream>
#include <math.h>

using namespace std;

double distance (float X1, float Y1, float Z1, float X2, float Y2, float Z2)
{
    return sqrt(pow((X2-X1),2)+ pow((Y2-Y1),2)+pow((Z2-Z1),2));
}

int main ()
{ 
    float x1, y1, z1,x2, y2,z2;
    ifstream file("D:\\points.txt");
    ofstream result ("D:\\result.txt");
    double bigdistance=0;

    if (file.is_open())
    { 
        while (!file.eof())
        {
            file>>x1>>y1>>z1;
            while (!file.eof())
            {
                file>>x2>>y2>>z2;
                double d= distance (x1,y1,z1,x2,y2,z2);
                if (bigdistance<d)
                {
                    bigdistance=d;
                    result<<x1<<y1<<z1<<endl<<x2<<y2<<z2;
                }
            }
        }
    }
    else cout <<"cannot open file";

    system ("PAUSE");
    return 0;
}

【问题讨论】:

  • 它没有做它应该做的事情,但它工作?即使你没有犯错误使用eof(),你仍然不会检查所有对。

标签: c++ max coordinates points minimum


【解决方案1】:

几个建议:

while (file >> x1 >> y1 >> z1 >> x2 >> y2 >> z2) {

}

将读取您的输入并在任何读取失败时停止。

您将需要读取整个输入并将其存储在点向量或类似的向量中。然后,您可以使用两个嵌套循环来迭代每对点。现在,您的程序假定输入文件包含所有对。也就是说,在内部循环中,从输入中多次读取每个点。

还有一些算法比二次算法更快,如果您有超过几千个输入点,您可能需要这些算法。参见例如this StackOverflow question

【讨论】:

  • 感谢您的所有回答。我真的是 C++ 和其他编程语言的新手。 Sjlver,你是对的,需要更快的算法,因为我的 txt 文件包含近 3000 个点。每条线都保存点坐标的 X、Y、Z 值。我想计算所有点之间的距离。像Point1->point2,point 1->point3.....point1 -->pointn; point2->point3, point2->point4....pointn;并使用这个距离,我想找到具有最小坐标的点和最大坐标的点。
  • 这里有我的txt文件的一行示例。 -18.810526 -6.0689259 -2.4343202
【解决方案2】:
#include <iostream>
#include<fstream>
#include <math.h>

using namespace std;
enter code here`{
    for (int i = 1; !f1.eof(); i++)
    {
        int x1, y1, x2, y2, x3, y3, x4, y4);
        read(f1, x1, y1, x3, y3);
        x2 = x3;
        y2 = y1;
        x4 = x1;
        y4 = y3;

        if (y4 > y1)
        {
            a = y1 - y4;
        }
        else
            a = y4 - y1;


        if (x4 > x3)
        {
            b = x4 - x3;
        }
        else
            b = x3 - x4;
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2013-02-27
    • 1970-01-01
    • 2020-08-23
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多