user15543957
user15543957

Reputation:

How can I get the middle from two numbers?

could someone please tell me if I´m on the right way or if I´m doing it totally wrong? How could I do it easier? I ´m thankful for any helpful tips I also get that i & mm cannot be resolved to a variable look at (1) I also get that double cannot covert to int look at (2)

Edit Update: I´m trying to do it with a try/catch and was coverting to a string instead of a double. But I´ve noticed that I can´t round it then. Isn´t try/catch a good idea?

/**
 * Returns the best guess given a range defined by its lowest and highest possible values.
 * The best guess that can be taken is the number exactly in the centre of the range.
 * If the centre is between two numbers, the number directly below the centre is returned (the centre is rounded down)
 * @param lowestPossible The lowest possible value of the range
 * @param highestPossible The highest possible value of the range
 * @return The best guess for the given range
 */
public static int getBestNewGuess(int lowestPossilbe, int highestPossible) {
    //return -1; // TODO: IMPLEMENT ME (AND DELETE THIS COMMENT AFTERWARDS!!!)

My Code:

    double x = (lowestPossilbe + highestPossible);
    double y = x /2; //Getting the middle
    
    if (int i = (int)y) { //if double y can be converted to a int then return int y       (1)
        return y;                                                                  //     (2)
    }else if (mm = (int) Math.round(y)) { //if that´s not the case, then round double y and convert it to a int    (1)
        int m = (int)y;
        return m; // return rounded and converted y
    }

    
//        if (roundf(y) == y) {

//          return y;

//        }if else {
//          
//        }
    
}

Upvotes: 0

Views: 1233

Answers (2)

simon3270
simon3270

Reputation: 732

If you are worried about overflow, and if you know that the lower value is less than the upper one, you could subtract the lower from the upper, divide the resulting int by 2, and add back to the lower number. Avoids casting a precise int to an approximate double and back again.

That simple case assumes that both numbers are positive. If the lower number is negative and the upper one positive, you need to add them and divide by 2, since subtracting a large negative number from a large positive one can overflow.

Upvotes: 1

Curtis
Curtis

Reputation: 558

Try this:

return Math.floor((Double.valueOf(lowestPossilbe) + Double.valueOf(highestPossible))/2)

Upvotes: 0

Related Questions