[英]how can I get the index of the max value in an array?
我有兩個數組
String[] city;
int[] temp;
它們的長度均為4。City擁有每個城市的名稱,而temp擁有每個城市的平均溫度。 臨時溫度與城市中的城市順序相同。 所以我的問題是,如何獲得temp中最大整數的索引? 我想打印出來
"The city with the highest average temperature is " + city[index] +
" with an average temperature of " + temp[max];
我想到了將最大int的索引引入city,然后將其插入city []。 由於數組的大小相同且順序相同,因此我只需要能夠返回int [] temp中最大值的索引;
如果您不想使用其他類,則可以執行以下操作。 您需要存儲最大值和最大值所在位置的索引,以便您還可以打印城市
String[] city = getCities (); // assuming this code is done
int[] temp = getTemparatures ();
int max = Integer.MIN_VALUE;
int index = -1;
for(int i = 0; i < temp.length; i ++){
if(max < temp[i]){
max = temp[i];
index = i;
}
}
System.out.println ("The city with the highest average temperature is " + city[index] +
" with an average temperature of " + temp[index]);
您可以使用<name>.length
獲得數組的長度。 [ .length - 1]` to get the item with the highest index. 數組的長度比最高索引大一倍,因此您應該使用' [ .length-1]`來獲得具有最高索引的項目。
抱歉,我在此編輯器中寫過,但本質是一樣的
int max = -100;
for (int i = 0; i < temp.length; i++){
if (temp[i] > max){
max = temp[i];
}
}
System.out.print("The city with the highest average temperature is " + city[your index] +
" with an average temperature of " + max);
您可以遍歷temp數組,找到max並將值存儲在變量中,然后在輸出語句中使用該變量。 以下是一些代碼,希望對您有所幫助
String[] city;
int[] temp;
int max = 0;
for(int i = 0; i < temp.size; i ++){
if(max < temp[i]){
max = temp[i];
}
}
"The city with the highest average temperature is " + city[max] +
" with an average temperature of " + temp[max];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.