0

我想获得双精度数组的最小值和其他两个最小值。总的来说,我想获得数组的 3 个较小的值。我没有使用类数组,但我使用的是double[].

4

4 回答 4

6

最简单的方法是打电话

Arrays.sort()

并取前 3 个值。

否则,您可以简单地循环遍历数组并跟踪三个最小的,就像最小的一样。

于 2011-03-14T23:01:10.007 回答
1
double[] dlist = {17.0, 10.0, 44, 7, 4.0, 33, 24, 10, 48.0, 49.0};
Arrays.sort (dlist);
System.out.println (dlist [0] + " " + dlist [1] /*...*/);
于 2011-03-14T23:08:10.297 回答
0

与上面类似,您可以循环并存储最小的一个,然后从数组中删除。然后再做一次,一次又一次。但我认为上面提到的方法更有效。

于 2011-03-14T23:03:43.867 回答
0

好吧,如果您根本不能使用 Arrays 类,您可能需要 3 个变量,一个来保存您尝试获取的每个值。只需将它们设置为等于数组中的前 3 个元素(如果至少有 3 个,否则只设置其中的几个)。

然后使用 for 循环遍历数组中的其余元素。如果一个元素小于您已经找到的一个或多个数字,请去掉这些数字中的最大数字,并将这个数字添加到最小数字列表中。

1. declare 3 variables
2. set variables equal to first 3 elements in array
3. loop from index 3 (4th element) to the length of the array
   a. see which of the already found numbers is bigger than the current element (if any)
   b.replace the biggest of the found numbers with the new number if at least one was found
4. print out or return the numbers you found
于 2011-03-15T01:59:43.077 回答