试图查找数组中点之间的最小距离时的随机垃圾输出

时间:2019-07-13 13:30:29

标签: c++ c++14 closest-points

有什么大惊小怪的?

我正在尝试查找点之间的最小距离(二维平面中2个点之间的距离:距(x1, y1) to (y1, y2))的距离,它们存储在数组arr中,然后计算并返回最小值那些距离。

但是,问题是我的源代码产生了随机垃圾输出。

这个想法是使用公式获得点(x1, y1) and (x2, y2)之间的距离: sqrt((x1 - x2)^2 + (y1 - y2)^2)。 为此,我为每个迭代选择4个元素:  x1 = arr[0], x2 = arr[1], y1 = arr[2], y2 = arr[3]x1x2在(i的每个迭代中保持不变,而x1, x2y1, y2之间的距离(对于{{1}的每个唯一迭代而变化})。最后,选择两点之间的最短距离并返回到j

我该怎么做才能解决这个问题?

在源代码中包含调试语句表明,罪魁祸首是随机垃圾值(从字面上看,它甚至不应该存在!)。

另一个罪魁祸首是main()给出了一个随机垃圾值。例如,当计算sqrt(arg)(4, 4)之间的距离时,结果为(1, 100)。但是相反,它输出sqrt(0 + (-99)^2) = 99

这是我的代码:

-2147483648

我知道这种方法是天真的,而且是O(n ^ 2),但是要使用更快的算法,我必须首先使用最基本的心理理智方法来解决它。

输入:

#include<iostream>
#include<vector>
#include<cmath>
using std::sqrt;
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int dist_cal(vector<int>&, int);

int main()
{
    int num_pairs = -1;
    cout << "Enter the number of pairs of point co-ordinates (x, y) that you want to enter: " << endl;
    cin >> num_pairs;

    vector<int> points;
    cout << "Now enter the (x, y) co-ordinate pairs: " << endl;
    for (int i = 0; i < num_pairs * 2; i++)
    {
        int buff;
        cin >> buff;
        points.push_back(buff);
    }

    cout << "The minimum distance between the array of points entered is " << dist_cal(points, num_pairs) << "." << endl;
    return 0;
}

int dist_cal(vector<int>& arr, int num_pairs)
{
    int min_distance = -1, temp_distance = -1, x1, x2, y1, y2, itr_count = 0;
    for (int i = 0; i <= num_pairs; i += 2)
    {
        x1 = arr[i + 0];
        x2 = arr[i + 1];
        for (int j = i + 2; j <= num_pairs; j += 2)
        {
            y1 = arr[j + 0];
            y2 = arr[j + 1];
            temp_distance = sqrt((x1 - x2)^2 + (y1 - y2)^2);
            if (itr_count == 0)
            {
                min_distance = temp_distance;
                itr_count++;
            }
            if (min_distance > temp_distance)
            {
                min_distance = temp_distance;
            }
        }
    }
    return min_distance;
}

输出应为4 4 4 7 8 1 100 4 4

实际输出为: 0

我在这里做错了什么?也欢迎使用替代方法(以及更高效的算法)!提前致谢! :)

2 个答案:

答案 0 :(得分:2)

在C ++中,^表示按位异或,如果要将x1-x2升为2的幂,可以编写:(x1-x2) * (x1 - x2)或使用std::pow函数。 / p>

所以这个

sqrt((x1 - x2)^2 + (y1 - y2)^2);

应为:

sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));

另一个问题,sqrt返回实数,因此min_distancetemp_distance应该是doublefloat


您的向量具有以下形式的坐标:x(i),y(i),..

因此请阅读

    x1 = arr[i + 0];
    x2 = arr[i + 1];

是错误的,应该是:

    x1 = arr[i + 0];
    y1 = arr[i + 1];

在内循环中做同样的事情。


此外,您的内部循环应从0索引开始。而且,您必须检测针对给定的p点计算distance(p,p)(始终为0)时的情况,并跳过此迭代。然后,您将计算所有距离。

答案 1 :(得分:0)

除了rafix07建议的修复程序之外,为了使此源代码正确运行,还必须进行另一处更改:

for (int j = i + 2; j <= num_pairs; j += 2)

实际上应该是:

for (int j = i + 2; j <= num_pairs + 2; j += 2)

这是因为对于i对(数组大小:4-> 4)的输入,0最多可以达到值7。由于j也依赖于i,因此对4总共执行了i个增量。因此i最多必须为4,以便x1 = 4, x2 = 5, y1 = 6y2 = 7。另一方面,对于j对(数组大小:6-> 4)的输入,0最多为7。这是因为如果i == 4j == 6,则y1 = 6y2 = 7,即向量points中的最后一个索引。