所以我有一个数组,我知道如何找到最高值,但我不知道如何获得该值在数组中的位置。到目前为止的方法如下:
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]
语句时就会更新它。