如何在数组中找到最大值? [英] How to find the maximum value in an array?

查看:37
本文介绍了如何在数组中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我需要能够遍历数组并找到最大值.我将如何比较数组的元素以找到最大值?

In java, i need to be able to go through an array and find the max value. How would I compare the elements of the array to find the max?

推荐答案

有一个 max int 并将其设置为数组中的第一个值.然后在 for 循环中遍历整个数组,看看最大 int 是否大于当前索引处的 int.

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

这篇关于如何在数组中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆