有什么大惊小怪的?
我试图找到点之间的最小距离(二维平面中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]
.
x1
并且x2
在每次迭代 ( 的 ) 中保持不变,同时计算和( 的每次唯一迭代时变化i
) 之间的距离。最后,选择两点之间的最短距离并返回到。x1, x2
y1, y2
j
main()
我做了什么来解决这个烂摊子?
在源代码中包含调试语句表明罪魁祸首是随机垃圾值(从字面上看,它甚至不应该存在!)。
另一个罪魁祸首是sqrt(arg)
给出一个随机的垃圾值。例如,计算 和 之间的距离时(4, 4)
,(1, 100)
结果为sqrt(0 + (-99)^2) = 99
。但相反,它输出-2147483648
.
这是我的代码:
#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;
}
我知道这种方法是幼稚的并且 O(n^2),但是要转向更快的算法,我必须首先用最基本的方法来解决它,以保持精神健全。
对于输入:
4
4 4
7 8
1 100
4 4
输出应该是0
。
实际输出如下:
The minimum distance between the array of points entered is -2147483648.
我在这里做错了什么?也欢迎替代(和更有效的算法)!提前致谢!:)