Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...