求出数组中的最值与求出数组中的最值

数组获取最大值元素 
  最大值获取:从数组的所有元素中找出最大值。
  实现思路
  定义变量,保存数组0索引上的元素
  遍历数组,获取出数组中的每个元素
  将遍历到的元素和保存数组0索引上值的变量进行比较
  如果数组元素的值大于了变量的值,变量记录住新的值
  数组循环遍历结束,变量保存的就是数组中的最大值

 

最大值

public class day03 {
    public static void main(String[] args) {
        int[] array={5,15,30,20,100000,};

        int max = array[0];//比武擂台
        for (int i = 1; i < array.length; i++) {
            //如果当前元素,比max更大,则换人
            if (array[i]>max){
                max = array[i];
            }

        }
        //谁最后最厉害,就能在max当中留下谁的战斗力
        System.out.println("最大值:"+max);
    }
}

最小值

public class day04 {
    public static void main(String[] args) {
        int[] array={5,15,30,20,100000,-20};

        int min = array[0];//比武擂台
        for (int i = 1; i < array.length; i++) {
            //如果当前元素,比min更小,则换人
            if (array[i]<min){
                min = array[i];
            }

        }
        //谁最后最厉害,就能在max当中留下谁的战斗力
        System.out.println("最小值:"+min);
    }
}

 

 

posted @ 2022-06-29 20:03  zj勇敢飞,xx永相随  阅读(72)  评论(0编辑  收藏  举报