Java基础系列 - 查找数组的最大值和最小值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package com.test6; public class test5 { public static void main(String[] args) { int [] arr = { 1 , 2 , 31 , 4 , 5 , 6 , 7 , 88 , 9 , 11 , - 1 }; float [] arr2 = { 1 , 2 , 31 , 4 , 5 , 6 , 7 , 88 .88f, 9 , 11 .1f, -1f}; ArrayHelper ah = new ArrayHelper(); ah.GetMinAndMax(arr); ah.GetMinAndMax(arr2); /** 打印显示 数组元素包括:1 2 31 4 5 6 7 88 9 11 -1 数组的最大值是:88 数组的最小值是:-1 数组元素包括:1.0 2.0 31.0 4.0 5.0 6.0 7.0 88.88 9.0 11.1 -1.0 数组的最大值是:88.88 数组的最小值是:-1.0 */ } } class ArrayHelper { public void GetMinAndMax( int [] arr) { int min = arr[ 0 ]; int max = arr[ 0 ]; System.out.print( "数组元素包括:" ); for ( int i = 0 ; i < arr.length; i++) { System.out.print(arr[i] + " " ); if (arr[i] > max) // 判断最大值 max = arr[i]; if (arr[i] < min) // 判断最小值 min = arr[i]; } System.out.println(); System.out.println( "数组的最大值是:" + max); // 输出最大值 System.out.println( "数组的最小值是:" + min); // 输出最小值 } public void GetMinAndMax( float [] arr) { float min = arr[ 0 ]; float max = arr[ 0 ]; System.out.print( "数组元素包括:" ); for ( int i = 0 ; i < arr.length; i++) { System.out.print(arr[i] + " " ); if (arr[i] > max) // 判断最大值 max = arr[i]; if (arr[i] < min) // 判断最小值 min = arr[i]; } System.out.println(); System.out.println( "数组的最大值是:" + max); // 输出最大值 System.out.println( "数组的最小值是:" + min); // 输出最小值 } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步