1

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. 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

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! :)

1 Answers1

3

You're rounding both to two decimal places - it's just that 9.2999999 rounded is 9.30.

Change your 100s to 10 to round to a single decimal place in each case.

CupawnTae
  • 14,192
  • 3
  • 29
  • 60