在数组中查找最大值和最小值的索引
finding the index of max and min in an array
这是我的代码。我正在使用 bluej IDE.
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
if (num[i] < smallest) smallest = num[i];
if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
if (num[i] != smallest) countsmall++;
if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}
我试图在我成功找到的数组中找到最小值和最大值。之后,我试图找到它的索引。我创建了一个变量计数,然后遍历数组。如果数组中的该项不等于最小值或最大值,则 count+= count。但是,由于某种原因它不起作用。代码编译但 returns 错误值。请记住,我不允许使用 java 库。非常感谢任何帮助,谢谢。
如果你还想要最大和最小的索引,你为什么不在一个循环中做呢?例如:
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i < num.length; i++){
if (num[i] < smallest) {
smallest = num[i];
countsmall=i;
}
if (num[i] > largest) {
largest = num[i];
countlarge=i;
}
}
int array[] = {countsmall,countlarge};
return array;
}
}
这是我的代码。我正在使用 bluej IDE.
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
if (num[i] < smallest) smallest = num[i];
if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
if (num[i] != smallest) countsmall++;
if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}
我试图在我成功找到的数组中找到最小值和最大值。之后,我试图找到它的索引。我创建了一个变量计数,然后遍历数组。如果数组中的该项不等于最小值或最大值,则 count+= count。但是,由于某种原因它不起作用。代码编译但 returns 错误值。请记住,我不允许使用 java 库。非常感谢任何帮助,谢谢。
如果你还想要最大和最小的索引,你为什么不在一个循环中做呢?例如:
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i < num.length; i++){
if (num[i] < smallest) {
smallest = num[i];
countsmall=i;
}
if (num[i] > largest) {
largest = num[i];
countlarge=i;
}
}
int array[] = {countsmall,countlarge};
return array;
}
}