java求最大值的三種方法java
public class maxtest { public static void main(String[] args) { //###################最大值最小值start###################// int[] aa = {4,2,17,5,22,8,13,6}; int max = aa[0]; int min = aa[0]; for (int i = 0; i < aa.length-1; i++) { if(aa[i] > max){ max = aa[i]; } } System.out.println("最大值"+max); for (int i = 0; i < aa.length-1; i++) { if(aa[i] < min){ min = aa[i]; } } System.out.println("最小值"+min); //###################最大值最小值end###################// } }
結果值spa
最大值22 最小值2
public class maxtest { public static void main(String[] args) { //###################三元運算符最大值最小值start###################// int[] aa = {4,2,17,5,22,8,13,6}; int max = aa[0]; int min = aa[0]; for (int i = 0; i < aa.length; i++) { max = (aa[i] < max ? max : aa[i]); } System.out.println("最大值"+max); for (int i = 0; i < aa.length; i++) { min = (aa[i] > min ? min : aa[i]); } System.out.println("最小值"+min); //###################三元運算符最大值最小值start###################// } }
結果值code
最大值22 最小值2
public class maxtest { public static void main(String[] args) { //###################最大值最小值(分開查找)start###################// int[] aa = {4,2,17,5,22,8,13,6,14,12,117,15,122,18,113,16,24,22,217,25,222,28,213,26,214,212,117,215,122,218,113,216}; int bb = aa.length/2; int bbmax = aa[0]; for (int i = 0; i < bb-1; i++) { if(aa[i] > bbmax){ bbmax = aa[i]; } } int ccmax = aa[bb]; for (int i = 0; i < aa.length-1; i++) { if(aa[i] > ccmax){ ccmax = aa[i]; } } System.out.println("左最大值:"+bbmax); System.out.println("右最大值:"+ccmax); if(bbmax > ccmax){ System.out.println("結果值:"+bbmax); }else{ System.out.println("結果值:"+ccmax); } //###################最大值最小值(分開查找)end###################// } }
結束值class
左最大值:122 右最大值:222 結果值:222