如何理解为什么这不会返回最小值?

时间:2017-09-29 20:38:40

标签: java

请帮助理解为什么,在下面,我没有得到数组中最小值的输出。使用扫描仪输入值,程序也应输出最小数字。

**不使用.sort

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int[] list;
    list = new int[10000];
    int sum = 0;
    double avr = 0;
    int min = list [0];
    int max = list [0];
    int x = 0;
    int value;

    Scanner input = new Scanner(System.in);
    System.out.print("Add number " + (x + 1) + ": ");
    value = input.nextInt();

    while (x <= list.length && (value != -1 || x == 0)) {
        list[x] = value;
        x++;
        System.out.print("Add number " + (x + 1) + ": ");
        value = input.nextInt();
    }

    for (int i = 0; i < list.length; i++) {
        sum += list[i];
        avr = sum / x;

        if(list[i] > max)
            max = list[i]; 

        if( list[i] < min )
            min = list[i];

    }


    System.out.println("The sum of all values are: " + sum);
    System.out.println("The average value of the numbers are: " + avr);
    System.out.println("The maximum value of the numbers are: " + max);
    System.out.println("The minimum value of the numbers are: " + min);


}

}

1 个答案:

答案 0 :(得分:0)

我会建议最低限度的两项改进。

  1. 将您的min初始化为第一个value。现在你已经将min初始化为0,并且用户从不输入任何小于0的数字。这就是你持续0分钟的原因。
  2. 不要运行你的循环1000次。运行它的次数与非零元素一样多。
  3. 请参阅以下工作代码段:

     int[] list;
            list = new int[10000];
            int sum = 0;
            double avr = 0;
            int min = list [0];
            int max = list [0];
            int x = 0;
            int value;
    
            Scanner input = new Scanner(System.in);
            System.out.print("Add number " + (x + 1) + ": ");
            value = input.nextInt();
            min = value;
            while (x <= list.length && (value != -1 || x == 0)) {
                list[x] = value;
                x++;
                System.out.print("Add number " + (x + 1) + ": ");
                value = input.nextInt();
            }
    
            for (int i = 0; i < list.length && list[i] !=0; i++) {
                sum += list[i];
                avr = sum / x;
    
                if(list[i] > max)
                    max = list[i]; 
    
                if( list[i] < min )
                    min = list[i];
    
            }
    
    
            System.out.println("The sum of all values are: " + sum);
            System.out.println("The average value of the numbers are: " + avr);
            System.out.println("The maximum value of the numbers are: " + max);
            System.out.println("The minimum value of the numbers are: " + min);