2019独角兽企业重金招聘Python工程师标准>>>
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###################//
}
}
结果值
最大值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###################//
}
}
结果值
最大值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###################//
}
}
结束值
左最大值:122
右最大值:222
结果值:222