Java輸出最大值,最小值3種方法
阿新 • • 發佈:2021-01-07
文章目錄
if語句
- if語句,輸入三個數,輸出對應的最大值,最小值
public static void main(String[] args) {
int max;
int a = 12, b = 34, c = 20;
if (a > b && a > c) {
max = a;
} else if (b > a && b > c) {
max = b;
} else {
max = c;
}
System.out.printf("最大值:%d\n",max);
int min;
if (a < b && a < c) {
min = a;
} else if (b > a && b > c) {
min = b;
} else {
min = c;
}
System.out.printf("最小值:%d",min);
}
輸出結果:
Scanner輸入三個數
- 加入Scanner,輸入三個數判斷大小並輸出最大值,最小值
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("輸入第一個數:");
int a = sc.nextInt();
System.out.println("輸入第二個數:");
int b = sc.nextInt();
System.out.println("輸入第三個數:");
int c = sc.nextInt();
int max = a > b ? a : b;
max = max > c ? max : c;
System.out.printf("三個數中最大值:%d\n", max);
int min = a < b ? a : b;
min = min < c ? min : c;
System.out.printf("三個數中最小值:%d", min);
}
輸出結果:
陣列輸入輸出n個數
- 從鍵盤輸入n個數,輸出這n個數的最大值,最小值
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入所需整數的個數:");
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int max = a[0];
int min = a[0];
for (int i = 0; i < n; i++) {
if (max < a[i]) {
max = a[i];
}
if (min > a[i]) {
min = a[i];
}
}
System.out.printf("最大值:%d\n", max);
System.out.printf("最小值:%d", min);
}