我怎样才能从两个数字中得到中间?

How can I get the middle from two numbers?

有人可以告诉我我的做法是正确的还是完全错误的? 我怎样才能做得更容易?我感谢任何有用的提示 我还了解到 i & mm 无法解析为变量查看 (1) 我也知道 double 不能隐蔽到 int 看 (2)

编辑更新: 我试图用 try/catch 来完成它,并且正在转换为字符串而不是双精度。但是我注意到那时我无法将其舍入。 try/catch 不是个好主意吗?

/**
 * 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!!!)

我的代码:

    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 {
//          
//        }
    
}

试试这个:

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

如果担心溢出,知道下位小于上位,可以用上位减去下位,再除以2,再加回下位.避免将精确的 int 转换为近似的 double 并再次返回。

这个简单的例子假设两个数字都是正数。如果小数是负数,大数是正数,你需要将它们相加并除以2,因为从一个大的正数中减去一个大的负数会溢出。