簡體   English   中英

數組中最小的數字,不為0

[英]Smallest number in array that is not 0

試圖在不為0的數組中查找最小值,因為該數組幾乎總是有空值,我已經走了這么遠,但一直堅持如何停止尋找0的值

 float smallest = Integer.MAX_VALUE; 
for(int x=0; x<priceArr.length;x++) {
    if(smallest > priceArr[x]) {
    smallest = priceArr[x];
    }
}

通常,要將double s與==進行比較,可以使用epsilon值考慮其表示形式中的誤差裕度。
但是這種解決方案也不是完美的。
您可以參考這篇文章

默認float值為0.0F
因此,您可以在if語句中使用此條件:

float epsilon = 0.00000001F;

float currentValue = priceArr[x];
if (Math.abs(currentValue) < epsilon && smallest > currentValue ) {
   smallest = currentValue;
}

請注意,使用局部變量存儲priceArr[x]值會減少重復。

但是要當心,通過使用epsilon比較float可能會給出匹配,而該值實際上不是0值。
例如:

float[] array = new float[5];
array[0] = 0.000000001F;
float epsilon = 0.00000001F;

if (Math.abs(array[0]) < epsilon) {
    System.out.println("match");
}

會產生“匹配”。

如果您的要求只是忽略未顯式賦值的數組元素,則應優先使用Float不是float
Float在數組中默認為null ,因此您可以測試null以忽略元素:

Float currentValue = priceArr[x];
if(currentValue != null && smallest > currentValue ) {
   smallest = currentValue;
}

試圖在不為0的數組中找到最小值

該過程與從數組中找到最小的過程相同。 最重要的是,添加條件以檢查當前搜索不為零。

float smallest = Integer.MAX_VALUE; 
for(int x=0; x<priceArr.length; x++) {
    if(smallest < priceArr[x] && priceArr[x] != 0) {    //additional condition here
        smallest = priceArr[x];
    }
}

注意 :從smallest > priceArr[x]smallest < priceArr[x]

如果數組大小至少為1,則還可以將smallest設置為第一個數組元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM