简体   繁体   English

舍入一个双精度到一个十进制位置不起作用。

[英]Rounding a double to one Decimal place not working.

first of all i'd like to point out that i know this is a topic covered a lot but after about an hour of looking at other questions and trying what is suggested there i still can't get this to work. 首先,我想指出,我知道这是一个很多话题,但经过大约一个小时的查看其他问题并尝试在那里提出建议后,我仍然无法让这个工作。

I'm performing a binary search through Performances for numbers that are within 0.1 of a given number time. 我正在通过Performances对给定数字时间内0.1的数字执行二进制搜索。 however, i need both the min/max targets and the number we are searching with (average) to be rounded to only one decimal place. 但是,我需要将最小/最大目标和我们搜索的数字(平均值)四舍五入到只有一个小数位。 the method assumes that performance is sorted in ascending order. 该方法假定性能按升序排序。

        public static int binarySearch(Performance[] performances, double time) {


    if (performances == null){
    return -1;
    }



    int first = 0;
    int last = performances.length - 1;
    double targetMax = time + 0.1;
    double targetMin = time - 0.1;
    targetMax = Math.round((targetMax * 100)) / 100.0;
    targetMin = Math.round((targetMin * 100)) / 100.0;


    while (first <= last){
                int mid = (first + last)/2;
                double average = performances[mid].averageTime();
                average = Math.round((average * 100)) / 100.0;

                if ((targetMax > average) && (targetMin < average)  ){
                        return mid; 
            }
                else if(average < targetMin){

                    last = mid -1;

                }

                else {
                    first = mid + 1;
                }


    }

            return -1;

}

here's where it gets weird. 这里变得奇怪。 the rounding i have done seems to work fine for targetMax and targetMin with 9.299999999 rounding to 9.3, however when rounding average down from 9.3333333333 it returns 9.33 我已经完成的舍入似乎对于targetMax和targetMin工作正常,其中9.299999999舍入到9.3,但是当从9.3333333333舍入平均值时它返回9.33

i really am stumped on this one, aren't i doing the exact same thing to both variables? 我真的很难受这个,我不是对两个变量做同样的事吗?

new to this website so please excuse anything i've left out, just ask and ill edit it in. trying my best! 这个网站是新的,所以请原谅我遗漏的任何东西,只是问问题并且编辑它。尽我所能! :) :)

You're rounding both to two decimal places - it's just that 9.2999999 rounded is 9.30. 你将两个四舍五入到小数点后两位 - 只是9.2999999舍入为9.30。

Change your 100 s to 10 to round to a single decimal place in each case. 在每种情况下,将100秒更改为10以舍入到单个小数位。

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

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