arrays - C++ , Finding the lowest value, Function Error: Loop will run at most one (Loop increment never executed)

问题描述:

So I'm trying to create a function to read 5 doubles ( which will be input by a user through the main function) and return the minimum value.

I was considering creating an array and assigning these 5 numbers to it. Then looping through the array and comparing new values with the first item in that array.

I receive the following error though: Loop will run at most one (Loop increment never executed).

Please check the code below. Any advice where it went wrong?

double findLowest(double a, double b, double c, double e, double f)

{

// creating an array numberRange[] to read the 5 input double values

double numberRange[] = {a,b,c,e,f};

// creating a variable minimum and assigning it the value of the

// first item in the numberRange[] array

double minimum = numberRange[0];

// looping through the numberRange array

for(int counter = 1; counter < sizeof(numberRange) ; counter++ )

{

// checking if the numberRange value at the counter is less than

// the minimum value. If true, the minimum value is replaced with

// a new value.

if ( numberRange[counter] < minimum )

{

minimum = numberRange[counter];

}

return minimum;

}

}

网友答案:

The reason for that warning is because you have return minimuminside the loop. So you will immediately leave the function during the first iteration of the loop. That statement should be after the loop is done.

Also, your counter test is incorrect. sizeof(numberRange) is the number of bytes in the array. But each number is more than one byte; if a double is 8 bytes, sizeof(numberRange) will be 5 * 8 = 40, and you'll try to read past the end of the array. To get the number of elements in an array, you have to divide the size of the array by the size of each element, so it should be

counter < sizeof(numberRange)/sizeof(*numberRange)

网友答案:

sizeof(numberRange) = 40

Would you like to loop 40 times? Each double take 8 bytes in your memory. So sizeof() tell you the space not the lenght of your array ...