簡體   English   中英

如何在數組中找到最大值及其位置

[英]How to find the highest value in an array and its position

所以我有一個數組,我知道如何找到最大值,但我不知道如何獲取該值在數組中的位置。 到目前為止的方法如下:

 public static void findHottest(int[] temp){
        int hottest = temp[0];
        for(int i = 1; i < temp.length; i++){
            if(temp[i] > hottest) {
                hottest = temp[i];
            }
        }
public static void findHottest(int[] temp){
    int hottest = temp[0];
    int highestIndex = 0;

    for(int i = 1; i < temp.length; i++){
        if(temp[i] > hottest) {
            hottest = temp[i];
            highestIndex = i;
    }
}

當遇到更高的值時,只需存儲索引。

您已經有了答案。 在你的代碼中

    public static void findHottest(int[] temp){
            int hottest = temp[0];
int index =0;
            for(int i = 1; i < temp.length; i++){
                if(temp[i] > hottest) {
                    hottest = temp[i]; 
                    index =i // index is the index you are looking for.
                }
            }

因此,只要有一個index變量,只要執行hottest = temp[i]語句就可以更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM