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

不羁的心 提交于 2019-12-12 05:11:26

问题


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


来源:https://stackoverflow.com/questions/37548399/possible-loss-of-precision-with-mod-but-its-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!