我正在學習陣列,并試圖撰寫一個程式來找到陣列中最大的整數。該程式沒有給我預期的解決方案
我的代碼:
import java.util.*;
public class GreaterInt{
public static void main(String[] args){
System.out.println("Enter the size of the array");
Scanner sc = new Scanner(System.in);
//creating the dimesion for array
int size = sc.nextInt();
System.out.println("Enter the values inside the array");
// Creating an array
int [] numbers = new int [size];
//entering the values in the array
for (int i = 0; i < size; i ){
numbers [i] = sc.nextInt();
}
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
for (int i = 0; i < numbers.length; i ){
if (numbers[i] < min){
min = numbers[i];
}
if (numbers[i] > max){
max = numbers[i];
}
}
System.out.println("The minimum value in the list of numbers is" max);
System.out.println("The maximum value in the list of numbers is" min);
}
}
我得到的結果:
Enter the size of the array
5
Enter the values inside the array
2
4
2
6
1
The minimum value in the list of numbers is2147483647
The maximum value in the list of numbers is-2147483648
uj5u.com熱心網友回復:
您的初始化不正確。你正在初始化你的 min 和 max 變數,比如
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
雖然應該是相反的
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
在您試圖找到最小數字的第一個 if 塊中,由于 min 已經等于 Integer.MIN_VALUE,因此 numbers[i] 的值不會低于該值,并且 if 條件永遠不會為真。
if (numbers[i] < min) {
min = numbers[i];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433416.html
下一篇:如何避免代碼中的大量縮進?
