给定一个数组,获取其中的最大。最小值

/*

获取最大值:

思路: 1.获取最大值需要进行比较,因为每一次比较都会有一个最大值,而这个值不确定,所以要定义一个变量max,临时存储这个最大值

    2. 假设最大值是数组中位置0的数值,数组中每一个数值都去和临时存储的最大值作比较,如果大于就替代成新的最大值

    3. 所有位置都比较完毕,最后的max就是最大值

步骤: 1. 定义变量max为数组中位置0的数值

    2.遍历数组

    3.定义判断条件,如果遍历到的数值比变量大,就赋值给变量max

*/

 1 //第一种方法演示
 2 class ArrayTest
 3 {
 4     public static int getMax(int[] arr)
 5     {
 6         int max = arr [0];
 7         for (int x =0; x<=arr.length-1; x++) //注意,此处如果length不减1,则结果会返回null
 8         {
 9             if (arr [x] > max)
10                  max = arr[x];                
11         }
12         return max;
13     }
14     public static void main(String[] args)
15     {
16         int [] arr = {1,3,8,9};
17         int max = getMax(arr);
18         System.out.println("max="+max);
19     }
20 }
View Code
 1 class ArrayTest
 2 {
 3     public static int getMax(int[] arr)
 4     {
 5         int max = 0;  //让max直接取角标的值
 6         for (int x =1; x<=arr.length-1; x++)
 7         {
 8             if (arr [x] > arr[max]) //两个角标对应的值对比
 9                  max = x;                //将对应角标赋值给max
10         }
11         return arr[max];
12     }
13     public static void main(String[] args)
14     {
15         int [] arr = {1,3,8,9};
16         int max = getMax(arr);
17         System.out.println("max="+max);
18     }
19 }
View Code

 

转载于:https://www.cnblogs.com/allison-aichipingguo/p/10659416.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值