gpt4 book ai didi

java - 在 Java 中显示数组元素的位置

转载 作者:行者123 更新时间:2023-12-01 15:33:33 25 4
gpt4 key购买 nike

我正在尝试显示数组中最大值的位置(索引)数。它是一个包含 100 个随机数的数组。由于某种原因,前几个数字之后的输出是正确的。我总是在输出的开头得到错误的数字。这是我的代码;谢谢

public static void main(String[] args) {
int max = 0;
int array[] = new int[100];
System.out.println();

// code to display student responses
randomNum(array);

System.out.println(" Survey Responses - 100 Students: ");
response(array);

System.out.println("Positions of the highest numbers");
System.out.println();

for (int i = 0; i < array.length; i++) {
max = Math.max(max, array[i]);
if (array[i] == max) {
System.out.println(i);
}
}
}

private static void randomNum(int A[]) {
for (int i = 0; i < A.length; i++) {
A[i] = (int) (Math.random() * 10000) % 10 + 1;
}

}

public static void response(int[] resp) {
for (int x = 0; x < resp.length; x++) {
System.out.print(resp[x] + " ");
}
System.out.println();
}

最佳答案

运行两个周期,如下所示:

for (int i = 0; i < array.length; i++) {
max = Math.max(max, array[i]);
}
for (int i = 0; i < array.length; i++) {
if (array[i] == max) {
System.out.println(i);
}
}

到目前为止,您输出的是前缀中看到的最大数字的索引,而不是等于总最大值的值的索引。

关于java - 在 Java 中显示数组元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com