c if-statement的最大值在数组中的最大值未指向正确的元素

C++ if-statement for maximum value in array not pointing to correct element

本文关键字:最大值 元素 if-statement 数组      更新时间:2023-10-16

我已经由机器人采取的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。)。这至少会更快。

您的特定问题是逻辑错误,因为您仅将新距离与前一个距离进行比较,而不是迄今为止找到的最小值。