问题
So this the line with the precision error fault;
A[i]= m % 3;
m is long A is int[]; And my error is error: possible loss of precision A[i]= m % 3. required int found long.
How can I have error when the only potential answers are 0,1,2? Isn't there another way than declaring A as long[]? It's a potentially big array so I don't want that (in fact I would even prefer for A to be short[]) Also I tried error: A[i]= m % 3L , but same result.
回答1:
The compiler doesn't look at the result, it looks at the type. The type of m%3
is long
, and you are trying to put it into an int
.
So, the compiler is angry, because potentially, the value stored in a long
is bigger than the one you can store into an int
.
In order to remove the problem, you have to cast the result back into an int
:
A[i] = (int) (m % 3);
However, you can do this because you know the result is 0,1 or 2. If you do not know the value of the long
you are casting, you may have an integer overflow:
public static void main(String[] args) {
long l = Integer.MAX_VALUE + 1L;
System.out.println(l);
// 2147483648
System.out.println((int)l);
// -2147483648
}
来源:https://stackoverflow.com/questions/37548399/possible-loss-of-precision-with-mod-but-its-not