Java求数组中的值最大元素

求数组中的值最大元素
自定义函数写法:
假设第一个元素 max 是最大值, for 循环遍历数组中元素,数组中的元素跟 max 比较,比 max 大就把它赋值给 max 作为新的比较值, 遍历完成 ,输出数组中的最大值。
代码:

在这里插入代码片public class TestDemo {
    
    
    /*
    1.找数组中的最大元素
     */
    public static void main(String[] args) {
    
    
        int[] array = {
    
    2, 52, 9, 10, 12, 26};
        int max = array[0];//假设第一个元素是最大值
        //for循环遍历数组中元素,每次循环 max跟数组索引为i的元素比较大小
        for (int i = 0; i < array.length; i++){
    
    
            if (max < array[i]){
    
    //数组中的元素跟max比较,比max大就把它赋值给max作为新的比较值
                max = array[i];
            }
        }
        System.out.println(max);//输出数组中的最大值
    }
}

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44436675/article/details/112084653