令 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 种解释:
0
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
。您还需要迭代输入数组的长度,而不是 0
到 largest
:
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);
public static void main(String[] args) {
int[] arr = {1, 2, -7, 4, 62, 2, 5};
System.out.println(maxAbs(arr));
}
public static int maxAbs(int[] arr) {
// public int greatestNegative(int[] list) {
int max = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
if (max == 0 || arr[i] > max) {
max = arr[i];
}
}
}
return max;
}
}