Methods of max and min are returning the same value when passed in an array of r
ID: 3627837 • Letter: M
Question
Methods of max and min are returning the same value when passed in an array of randomly generated #'s. I know that int pos needs to be used in the if statement of the while loop, but not sure where. please help and explain...//Calc max
private static double computeMax (double []randomNums)
{
int length = randomNums.length;
int pos = 0;
double max = randomNums [0];
double posMax = randomNums [pos];
while (pos<length)
{
if (posMax> max)
{
max= posMax;
posMax = randomNums [pos];
}
pos++;
}
return max;
}
//Calc Min
private static double computeMin (double []randomNums)
{
int length = randomNums.length;
int pos = 0;
double min = randomNums [0];
double posMin = randomNums [pos];
while (pos<length)
{
if (posMin< min)
{
min= posMin;
}
pos++;
}
return min;
}
Explanation / Answer
/*Hi, this looks like java so here is some sample code for finding max and min values of an arbitrary length array of random numbers. Please read full answer*/
private static double findMax(double[] array) {
double max = array[0];
for (int i = 0; i < array.length; i++) {
if(array[i] > max)
max = array[i];
}
return max;
}
private static double findMin(double[] array) {
double min = array[0];
for (int i = 0; i < array.length; i++) {
if(array[i] < min)
min = array[i];
}
return min;
}
Your while loops do not increment through the array. You have initialized the min/max value and your while loop correctly iterates the same number of how many elements are in the array.
Another issue is the use of the while loop. Using a for loop is more suitable, since your method will know exactly how many times to iterate. A while loop is used for an unknown condition, such as reading a file line by line until the end is reached.