【发布时间】:2017-10-27 08:09:12
【问题描述】:
我有一个整数数组,如下面的代码所示。我必须在数组中找到一对最大的数字。但有一个小转折。
请看下面的代码和输出。
public class ArraySort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { -9, -2, -10, -1, -4 };
int[] b = null;
int n = a.length;
int temp = 0;
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + ",");
}
System.out.println("\nPair of larger numbers");
for (int i = 0; i < n; i++) {
if (k < 2) {
if (a[i] > a[n - 1 - i]) {
System.out.println(a[i]);
} else {
System.out.println(a[n-1-i]);
}
}
k++;
}
}
}
其输出显示为
Ascending Order:
-10,-9,-4,-2,-1, 一对更大的数字 -1 -2
但不是将最大的数字显示为-1,-2。我必须显示-10和-9。即使数组包含负值,比较也应该没有减号。
【问题讨论】:
-
使用
Math.abs(...)获取绝对值 -
不使用 Math.abs() 方法有什么办法吗?
-
然后取较小的值......你说你只有负值。 我投票结束,因为这个问题不太可能在未来帮助某人
-
请解释一下你对
Math.abs()的看法。 -
a[i] = a[i] < 0 ? -a[i] : a[i];