为什么我对Bigdecimal数的排序方法无法排序? [英] Why does my sorting method for Bigdecimal numbers fails to sort?

查看:1348
本文介绍了为什么我对Bigdecimal数的排序方法无法排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我采用了某种排序方法,但是没有按我预期的那样工作,而且我不明白我可能在哪里犯错.

problem : i employed a certain sorting method, but it didn't work out as i expected and i fail to understand where did i possibly err.

我的代码将输入(即数字)作为字符串输入到字符串数组中,然后在我比较它们时将它们转换为Bigdecimal数字,然后将它们作为字符串重新排列在数组中

My code took input(which are numbers) as Strings into an string array and then converted them into Bigdecimal numbers while i compared them, and then rearranged them accordingly in the array as strings

相关代码:

 String s[]={-100, 50, 0, 56.6, 90, 0.12, .12, 02.34, 000.000};

    for(int i=0;i<n-1;i++)
        {
            for (int j =i+1; j<n; j++) 
             {
              BigDecimal  d = new BigDecimal(s[j]); 
              BigDecimal a = new BigDecimal(s[i]);
                if(a.compareTo(d)==-1) 
                    {
                        String m = s[j];
                        s[j]=s[i];
                        s[i]=m;
                    }
              }
        }
         //output :90, 56.6, 50, 02.34, .12, 0.12, 0, 000.000, -100

        //expected output :90, 56.6, 50, 02.34, 0.12, .12, 0, 000.000, -100

约束:s[n]应该是一个字符串数组,如果两个输入具有相同的值,则它们应按照我们输入它们的顺序在数组中列出.

Constraints : s[n] should be a string array and if two inputs have same values they should be listed in the array in the same order we entered them.

我不明白为什么0.12和.12的输出顺序与我输入时的顺序不同,如果算法有误,那么即使0和000.000也不应以我输入它们的顺序出现,但是他们却做到了.

i don't understand why 0.12 and .12 are not output in the same order as i entered them, if the algorithm is somewhere wrong then even 0 and 000.000 should not have have appeared in the same order as i entered them, but instead they did.

推荐答案

好吧,由于您要使用字符串数字,因此必须将其用引号引起来,但是排序可以提高可读性.我建议以下

Well, since you want to use String numbers, you will have to wrap them in quotations, but your sorting can be much more readable. I would suggest the following

    String[] numbers ={"-100", "50", "0", "56.6", "90", "0.12", ".12", "02.34", "000.000"};
    List<BigDecimal> decimalList = new ArrayList<>();
    for(String s: numbers){
        decimalList.add(new BigDecimal(s));
    }
    Collections.sort(decimalList);
    Collections.reverse(decimalList);     // edit , forgot this line
    decimalList.forEach(System.out::println);

这篇关于为什么我对Bigdecimal数的排序方法无法排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆