簡體   English   中英

如何找到數組中最大的負整數?

[英]How do I find the largest negative integer in an array?

讓 test12 = [-1, -2, -3];

我被困在這一點上。 我在正整數上使用了以下內容,但我不確定要為負數更改什么。

 let test = [1 , 2, 3]; var largest= 0; for (i=0; i<=test.length;i++){ if (test[i]>largest) { largest=test[i]; } } console.log(largest);

數組中最大的負整數

你的問題可以有3種解釋:

  1. 0最遠的負整數
  2. 最接近0的負整數
  3. 一般最大的數字(如果出現全負整數數組,您可能會遇到困難,因為您將 min 初始化為 0)

只是為了澄清,最小的是“離零最遠”。 但這里有所有三種方式:):

 const ints = [-3, -2, -1, 0, 1, 2] const negativeInts = ints.filter(i => i < 0) const smallestNegative = Math.min(...negativeInts) const largestNegative = Math.max(...negativeInts) const largestOverall = Math.max(...ints) console.log({smallestNegative, largestNegative, largestOverall}) // -3, -1, 2

希望這可以幫助。 干杯。

只需將largest初始化為-Infinity而不是0 您還需要遍歷輸入數組的長度,而不是0largest

 let test12 = [-1, -2, -3]; var largest = -Infinity; for (i = 0; i < test12.length; i++) { if (test12[i] > largest) { var largest = test12[i]; } } console.log(largest);

另一種方法是傳播到Math.max

 let test12 = [-1, -2, -3]; console.log( Math.max(...test12) );

最大的負數是-244 ,因此您可以排序並獲取第一個索引。

 let arr = [-1, -2, -244, -7], [largets] = arr.slice().sort((a, b) => a - b); console.log(largets);

嘗試這個..

 var array = [-155,3, 6, 2, 56, 32, 5, -89, -32,115,-150]; array.sort(function(a, b) { return a - b; }); console.log(array[0]);

如果您想要一個編程解決方案,例如即使給出全負數組,您的程序也需要執行的編輯,請嘗試以下操作:

 let test = [-10, -1, -2, -3]; // just Assign largest to the first element in test. // the largest int might not be greater than zero, // but will definitely be larger that any other element in the array. var largest= test[0]; for (i=0; i<=test.length;i++){ if (test[i]>largest) { largest=test[i]; } } console.log(largest);

暫無
暫無

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

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