c if-statement的最大值在数组中的最大值未指向正确的元素
C++ if-statement for maximum value in array not pointing to correct element
我已经由机器人采取的2500个步骤的数组,每个步骤都以随机方向(向上,向下,右或左)进行。我应该存储从机器人起源的每个步骤的欧几里得距离(正确的三角形的斜边)。那里没问题。
我也应该将标签保持在最大上。欧几里得距离机器人到达,因此,如果当前距离大于以前的距离,那么当前的距离将成为新的最大距离。这是我的代码:
int main(){
int steps[2500];
int randDir[2500];
int coords[2] = {0,0};
int path[2500][2];
double eucliDist[2500];
eucliDist[0] = 1;
double maxEucliDist;
double taxiDist;
for (int i = 0; i < 2500; i++){
randDir[i] = rand() % 4;
steps[i] = i + 1;
switch(randDir[i]){
case 0:
coords[0] = coords[0] + 1;
break;
case 1:
coords[1] = coords[1] + 1;
break;
case 2:
coords[0] = coords[0] - 1;
break;
case 3:
coords[1] = coords[1] - 1;
break;
}
eucliDist[i] = sqrt((pow(coords[0],2)) + (pow(coords[1],2)));
if (eucliDist[i] > eucliDist[i-1]){
maxEucliDist = eucliDist[i]; //need to fix this. Not showing true max Euclid. Dist.
taxiDist = abs(coords[0]) + abs(coords[1]);
}
//cout << "Step " << steps[i] << " Euclidian distance from origin is: " << eucliDist[i] <<endl; //check euclidian dist each step
//cout << steps[i] << "t Coords (" << coords[0] << ", " << coords[1] << ")" << "n"; //check coords with each step
}
cout << "Final Coordinates: (" << coords[0] << ", " << coords[1] << ")" << endl;
cout << "Maximum Euclidian distance was: " << maxEucliDist << endl;
cout << "'Taxicab' distance is: " << taxiDist << endl;
cin.get();}
问题是我的输出显示了错误的最大值,如下面输出的摘要所示:
程序输出显示不正确的最大欧几里得距离
fyi,"出租车"距离是第二个机器人必须需要的距离,以便在需要时到达最大距离的第一个机器人位置(这是一个正确的三角形的基本 高度以来,自从网格上行驶以来)。
不确定我在做什么错。可能与我在代码下半部的if stategent有关。
有什么想法?
您的问题确实是您的IF-Statement:
if (eucliDist[i] > eucliDist[i-1]){ // THIS IS WRONG
maxEucliDist = eucliDist[i]; // THIS IS ACTUALLY OK
taxiDist = abs(coords[0]) + abs(coords[1]);
}
您正在将当前距离与上一个帧中的距离进行比较,而不是最大值。您还需要初始化您的最大值至零,因为它也需要一些开始,否则您的比较将是"当前的"与"垃圾")。C 确实不是初始化局部变量为零。
您的新if-Statement应该是这样的:
if (eucliDist[i] > maxEucliDist){
maxEucliDist = eucliDist[i];
taxiDist = abs(coords[0]) + abs(coords[1]);
}
您的第一个工作是认识到正数的平方是数字的单调函数。因此,请停止将这些正方形的根部遍及整个地方(计算机很难进行评估),并以距离平方进行工作,直到您显示最终结果为止。
然后,您可以用x * x
替换讨厌的pow(x, 2)
功能,并在整数算术中工作。(虽然采取步骤避免溢出int
。)。这至少会更快。
您的特定问题是逻辑错误,因为您仅将新距离与前一个距离进行比较,而不是迄今为止找到的最小值。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用指针从C++中的数组中获取最大值
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 整数溢出,最大值为 pow(10,19)
- 以C++递归方式查找向量中的最大值
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 查找包含 N 个元素的数组的最小值和最大值
- 如何在 c++ 中创建对的优先级队列.这会弹出具有最小值的元素.默认的弹出最大值
- 查找元组元素 C++ 的最大值
- c if-statement的最大值在数组中的最大值未指向正确的元素
- 查找容器中高于阈值的最大值和最小值元素
- 函数,它接受三个参数:指向双数组的指针、指向最小值的指针和指向最大值元素的指针
- std::bitset中的元素数量是否有最大值
- 二进制搜索,用于查找排序数组中比给定值最小和最大的元素
- 查找向量中最小+最大值元素的函数
- 元素最大值和特征值中的正部分