0

In this code snippet my main class calls isPerfectSquare() and if it returns true, getM() is called.

when getM() is called, if I remove the (int) casting where the int m is assigned, I get a compiler error (Incomparable Types: possible lossy conversion from double to int).

My question is; how is it that the compiler thinks that the code can return a double when the former method checks if the int total passed to it is a perfect square?

(if this is not considered a good question please tell me why)

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);
}
14k.wizard
  • 41
  • 6
  • 2
    You can't expect the compiler to _know_ you're always going to call `isPerfectSquare` before `getM`. Even if that were in the same method, it won't do it. – Tunaki Jan 16 '17 at 20:36
  • 4
    "how is it that the compiler thinks that the code can return a double" [Because `Math.pow` is defined to return a `double`](https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#pow(double,%20double)). – Salem Jan 16 '17 at 20:38
  • 2
    Pretty simple: **you** know `total` is a perfect square, since you call `isPerfectSquare()` before you do so. The compiler on the other hand only knows `Math.sqrt()` returns a value of type `double`. Or ignoring the knowledge-question completely: `Math.sqrt()` returns `double`. Converting `double` to `int` is **always** lossy, no matter whether the `double` has a decimal part or not. –  Jan 16 '17 at 20:46
  • Use rounding before integer conversion to avoid false negatives where the double result is a little bit too small. -- Avoid in the second procedure floating point computations and conversions by replacing `Math.pow(n,2)` with `n*n`. – Lutz Lehmann Jan 17 '17 at 09:10

0 Answers0