Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

java - possible loss of precision-with mod- (but it's not)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 longis 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...