在对整数求平方时,可能从double转换为int

时间:2017-01-16 20:34:39

标签: java math

在这段代码中,我的主类调用isPerfectSquare(),如果返回true,则调用getM()。

当调用getM()时,如果我删除了分配int m的(int)转换,我得到一个编译器错误(无法比较的类型:可能有损转换从double到int)。

我的问题是;当前一个方法检查传递给它的int总数是否是一个完美的正方形时,编译器怎么认为代码可以返回一个double?

(如果这不是一个好问题,请告诉我原因)

private static boolean isPerfectSquare(int total)
{
    int square = (int) Math.sqrt(total);
    //test
    System.out.print(square);

    return square * square == total;
}

/*Returns the sum value that should be returned by adding 
the magic square sides and diagonals*/
//m is global var

private static void getM(int total)
{
    int n = (int) Math.sqrt(total);

    m = (int) (n*(Math.pow(n, 2) + 1)/2);
}

0 个答案:

没有答案