简体   繁体   English

在Java中排序双打

[英]Sorting doubles in java

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
    String line;

    while ((line = in.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line);
        int len = st.countTokens();
        Double[] seq = new Double[len];
        for (int i = 0; i < len; i++)
            seq[i] = Double.parseDouble(st.nextToken());
        Arrays.sort(seq);
        for (int i = 0; i < len; i++) {
            if (i > 0) System.out.print(" ");
            System.out.print(seq[i]);
        } System.out.print("\n");
    }
}
}

So I'm trying to solve this CodeEval problem ( https://www.codeeval.com/open_challenges/91/ ) and my solution is not getting through all the test cases. 因此,我正在尝试解决此CodeEval问题( https://www.codeeval.com/open_challenges/91/ ),而我的解决方案并未遍历所有测试用例。 I think my method of output is correct (spaces between numbers, trailing newline). 我认为我的输出方法是正确的(数字之间的空格,尾随换行符)。 I can't figure out what may be going on in the sorting or anywhere else. 我不知道排序或其他任何地方可能会发生什么。

The solution is apparently not correct when using floats either. 当使用浮点数时,该解决方案显然也不正确。

You may be sorting correctly but printing incorrectly. 您可能排序正确,但打印不正确。 Decimal numbers are represented approximately. 十进制数近似表示。 The runtime attempts to show them in the short format, but that is not guaranteed. 运行时将尝试以短格式显示它们,但不能保证。

All the examples they gave should work, but who knows what the test suite does in the background. 他们提供的所有示例都可以使用,但是谁知道测试套件在后台执行的操作。

I also think this is a printing problem. 我也认为这是打印问题。 The output seems to require exactly 3 decimal places on each number, based on the sample I/O. 根据样本I / O,输出似乎要求每个数字正好小数点后三位。 But, if you print out a double like 70.920 (one of the example inputs) it will display as 70.92 . 但是,如果您打印出像70.920这样的双70.920 (示例输入之一),它将显示为70.92

double d = 70.920;
System.out.println(d);
System.out.printf("%.3f", d);  // <-- try this
70.92
70.920

Notice how the second output is consistent with the format of the sample output whereas the first is not. 请注意,第二个输出如何与示例输出的格式一致,而第一个则不一致。

I would use double not Double and I would only sort the values after reading the all, not after every line. 我将使用double而不是Double并且我只会在读取全部内容之后而不是在每一行之后对值进行排序。

Perhaps some inputs have more than one line? 也许某些输入有多行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM