I am trying to figure out why I am getting this loss of precision error in my Java program.
This is the error:
error: possible loss of precision
int digit = num/Math.pow(10,i-1)%10;
^
required: int
found: double
1 error
This is the code clip inside a for loop
for(int i = 1; i<=String.valueOf(num).length(); i++)
{
int digit = num/Math.pow(10,i-1)%10;
//etc
}
I want to keep digit as an integer variable, and I tried to declare digit outside the loop, and I also tried casting it into an integer which didn't work. I did try doing it as:
digit += num/Math.pow(10,i-1)%10; //with digit declare outside of loop
which worked magically, but I don't want to increment it, instead I want it to contain the digit which I can use for later. Is there something I'm missing here? Please explain.
I tried to run your code as follows:
int digit = (int) (num/Math.pow(10,i-1)%10);
And it worked as expected, i.e. it iterated through the digits of your variable num (which I assumed as int).
When you use the += operator, it works not because of magic, but because of automatic type promotion. You can read more about it here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
The easist fix is to simply cast
num/Math.pow(10,i-1)%10;
into an Integer. You can do this by adding (int) before it:
int digit = (int) num/Math.pow(10,i-1)%10;
As to why this happens: Math.pow is defined as a double and won't convert a Double value into an Integer value without explicitly telling it to.
Math.pow
returns a double, and all your other operands in the expression are integral types. To fix the compiler error, explicitly cast the result of Math.pow
to an int, as indicated by the other answers.
Side note. Don't use Math.pow
to find 10 to the power of i-1, because floating-point exponentiation is unnecessarily expensive. Instead, multiply by 10 on every iteration, like so:
int r = 1;
for(int i = 1; r < num; i++, r *= 10) {
int digit = num / r % 10;
// ...
}