close
  • 給定任意10個數字,印出這10個數字,計算奇數和偶數各有多少及其最大值
public class P613 {	public static void main(String[] args) {
		// 給定之10個數字,以矩陣存放		int[] a = { 53, 27, 69, 12, 3, 96, 100, 214, 33, 87 };
		// count 存放偶數個數		int count = 0, odd, even;
		// odd 存放奇數最大值		// even 存放偶數最大值		// 並將兩者初始值設定為矩陣第一個元素值a[0]		odd = even = a[0];
		// 使用for迴圈逐一判斷a矩陣各元素是否為偶數		for (int i = 0; i < a.length; i++) {
			// 如a[i]為偶數,count加1			// 進if判斷a[i]是否大於even值			// 是,a[i]值指定給even			if (a[i] % 2 == 0) {				count++;				if (a[i] > even) {					even = a[i];				}
				// 當a[i]不是偶數,進else if				// 判斷a[i]是否大於odd值				// 是,a[i]值指定給odd			} else if (a[i] > odd) {				odd = a[i];			}
			// 印出各值			System.out.print(a[i] + " ");		}
		System.out.println();		System.out.println("陣列共有偶數: " + count + " 個");
		// count值為偶數個數,要知道奇數個數		// 只要用全部個數(a.length取得矩陣元素個數)減掉偶數個數(count)即可		System.out.println("陣列共有奇數: " + (a.length - count) + " 個");		System.out.println("陣列裡奇數最大值為: " + odd);		System.out.println("陣列裡偶數最大值為: " + even);	}}
  • 輸出結果:
53 27 69 12 3 96 100 214 33 87 陣列共有偶數: 4 個陣列共有奇數: 6 個陣列裡奇數最大值為: 87陣列裡偶數最大值為: 214
arrow
arrow

    ALVIN 發表在 痞客邦 留言(0) 人氣()