简体   繁体   中英

Finding the min and max number of an array

When I run this program, it finds the max number but always prints 0.0 as the minimum.

When I use Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY instead of setting smallest and largest to x[0], it works correctly.

Using Math.min and Math.max also gives me the same error but works with Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY as well. I looked at several other similar questions and I'm not allowed to use Array.sort or any of the other suggestions people post.

I just want to know why setting both variables to x[0] only ever works to find the largest number, whether I declare that variable first, second or set it equal (Double largest, smallest = x[0]).

public class MaxAndMin {
    public static void main (String[] args) {
        Scanner s= new Scanner(System.in);
        System.out.println("How many numbers would you like to enter?");
        int n= s.nextInt();

        double[] x= new double[n];
        double smallest= x[0]; //double smallest= Double.POSITIVE_INFINITY; 
        double largest= x[0]; //double largest= Double.NEGATIVE_INFINITY;

        for (int i=0; i<x.length; i++) {
            x[i]= kbd.nextDouble();

            if (x[i] > largest) {
                largest = x[i];

            } else if (x[i] < smallest) {
                smallest = x[i];
            }
        }
        System.out.println("Smallest number: " + smallest + " Largest number: " + largest);
    }
}

When you initialize smallest and largest , you haven't put any values into x , so its elements are just the default values that the array was created with, ie zero.

Hence, you will only find a smaller smallest value if one is less than zero (or a larger largest value if one is greater than zero).

You should use the POSITIVE_INFINITY and NEGATIVE_INFINITY to initialize the values, since all values are smaller and larger than these respectively.


Alternatively, you can initalize smallest = largest = x[0] in the for loop when i == 0 . However, the former approach is preferable, since it does not require checking i == 0 on every iteration.


Alternatively, you can move the first assignment out of the loop:

x[0] = smallest = largest = kbd.nextDouble();
for (int i = 1; i<x.length; i++) {
  x[i] = kbd.nextDouble();
  ...

This avoids checking i == 0 repeatedly, but you have to duplicate the kbd.nextDouble() . I'd still use the first approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM