获取数组中的最值

在数组中获取最大值之方法一
class ArrayDemo3
{
public static void main(String[] args)
{
int[] arr = {5,8,7,1,2,4,9};
int temp = getMax(arr);
System.out.println(temp);

}
public static int getMax(int[] arr)
{
     int max = arr[0];                     //先定义一个初始化变量
     for(int x=0;x<arr.length;x++)          //对数组进行遍历
      {
          if(arr[x]>max)                     //在遍历中判断条件。
             max = arr[x];
       }  
      return max;      //因为有具体返回值类型所以需要return一个值
 }

}

第二种方法:将max初始化为0,也就是用脚标进行
class ArrayDemo3
{
public static void main(String[] args)
{
int[] arr = {1,2,2,3,4,8,6,4};
int a = getMax(arr);
System.out.println(a);
}
public static int getMax(int[] arr)
{
int max = 0; //初始化临时变量为脚标值。
for(int x=0;x<arr.length;x++)
{
if(arr[x]>arr[max]) //比较时
max = x;
}
return(arr[max]);
}
}

获取最小值同理。

猜你喜欢

转载自blog.csdn.net/weixin_43247990/article/details/82990451