[英]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。 但是,由於某種原因,它不起作用。 代碼編譯但返回錯誤的值。 請記住,我不允許使用 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.