Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible loss of precision

Tags:

java

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);

 }
}
like image 278
Sandra Avatar asked Feb 27 '13 21:02

Sandra


1 Answers

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);
like image 188
Balázs Édes Avatar answered Oct 21 '22 05:10

Balázs Édes