Sandra
Sandra

Reputation: 107

Possible loss of precision

I am trying to run this code in java and getting following error, required int found double.

public class UseMath{
public static void main(String[]args){
  int x = Math.pow (2,4);
System.out.println ("2 to the power of 4 is" + x);

 }
}

Upvotes: 6

Views: 28586

Answers (1)

Balázs Édes
Balázs Édes

Reputation: 13807

If you take a look at the documentation, it says, that Math.pow() expects two doubles, and returns a double. When you pass ints to this function, it means no harm, because casting (converting) an int to double means no loss. But when you assign the value to an int, it means, it can lose precision.

Simply do this:

int x = (int)Math.pow(2,4);

or

double x = Math.pow(2,4);

Upvotes: 17

Related Questions