一千萬個為什麽

搜索

在數組上返回0的最小值(目標是查找最大值和最小值)

提前致謝。當我打印這個數組的最小值時,我無法弄清楚為什麽我的代碼會給我帶來麻煩。它似乎保留了min的初始0值,但我不確定如何糾正這個問題。 Max工作正常。我是否在程序的錯誤部分設置了最大值和最小值?

另外,這是我第一次使用數組,所以我可能會對稍後打印下標有一些疑問。

再次感謝!

編輯 - 據我所知,這解決了這個問題。謝謝Dan W.

 for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
        System.out.print("Enter a new number. This will continue until "
                + "you reach the size of the array. ");
        arrayOfNumbers[i] = keyboard.nextInt();
    }
            int max = arrayOfNumbers[0];
            int min = arrayOfNumbers[0];

package program8;

import java.util.Scanner;

public class arrayPrint {

    public static void main(String[] args) {
        final int NUMBER_OF_ELEMENTS;
      Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the amount of numbers the array will read in. ");
        NUMBER_OF_ELEMENTS = keyboard.nextInt();
                int arrayOfNumbers[] = new int[NUMBER_OF_ELEMENTS];
                int max = arrayOfNumbers[0];
                int min = arrayOfNumbers[0];
        for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
            System.out.print("Enter a new number. This will continue until "
                    + "you reach the size of the array. ");
            arrayOfNumbers[i] = keyboard.nextInt();
        }
        for (int i = 0; i < arrayOfNumbers.length; i++) {
            if (max <= arrayOfNumbers[i])
                max = arrayOfNumbers[i];
        }
        for (int i = 0; i < arrayOfNumbers.length; i++) {
            if (min >= arrayOfNumbers[i])
                min = arrayOfNumbers[i];
        }
                System.out.print(+max+ "max and " +min+ " min");
        }


}

最佳答案

你輸入什麽價值?因為 int 的默認值為0:這裏 因此,如果您只輸入正數,則min將始終為0。

為避免這種情況,請在用戶輸入數字後初始化最小值和最大值,這樣最大值和最小值不會默認為0。

轉載註明原文: 在數組上返回0的最小值(目標是查找最大值和最小值)