这是我到目前为止所拥有的
double[] num = {1.9, 2.9, 3.4, 3.5};
double max = num [0];
for (int i = 1 ; i < num.length ; i++)
{
if (num [i] > max)
max = num [i];
}
System.out.println ("Max is " + max);
我需要找到最大值的索引。我已经尝试通过在if语句中放入一个句子来打印索引,并且我也尝试将i存储到另一个变量中。他们都没有工作。
答案 0 :(得分:2)
您需要跟踪最大值及其索引。
public class GetMaxIndex {
public static void main(final String[] args) {
final double[] numbers = { 1.9, 2.9, 3.4, 3.5 };
double maxNumber = numbers[0];
int maxIndex = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxNumber) {
maxNumber = numbers[i];
maxIndex = i;
}
}
System.out.println("Max is " + maxNumber);
System.out.println("Index of max is " + maxIndex);
}
}
答案 1 :(得分:0)
double[] num = {1.9, 2.9, 3.4, 3.5};
double max = num[0];
int maxIndex = 0;
for (int i = 1 ; i < num.length ; i++)
{
if (num[i] > max)
{
maxIndex = i
max = num[i];
}
}
System.out.println("Max is " + max);
System.out.println("Max index is + maxIndex);