使用mod-可能会损失精度(但不是) [英] possible loss of precision-with mod- (but it's not)

查看:111
本文介绍了使用mod-可能会损失精度(但不是)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这条线有精度错误;

So this the line with the precision error fault;

A [i] = m%3;

A[i]= m % 3;

m长 A是int []; 我的错误是 错误:可能会失去精度 A [i] = m%3. 必需的int 发现很久.

m is long A is int[]; And my error is error: possible loss of precision A[i]= m % 3. required int found long.

当唯一可能的答案是0,1,2时,我怎么会出错? 除了声明A一样长,没有别的方法吗? 这是一个潜在的大数组,所以我不希望这样(实际上,我什至宁愿A短一些[]) 我也试过错误:A [i] = m%3L,但结果相同.

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.

推荐答案

编译器不查看结果,而是查看类型. m%3的类型是long,并且您试图将其放入int.

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.

因此,编译器很生气,因为存储在long中的值可能大于可以存储在int中的值.

So, the compiler is angry, because potentially, the value stored in a longis bigger than the one you can store into an int.

为了解决此问题,您必须将结果强制转换回int:

In order to remove the problem, you have to cast the result back into an int:

A[i] = (int) (m % 3);

但是,您可以执行此操作,因为您知道结果为0,1或2.如果您不知道要转换的long的值,则可能有整数溢出:

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
}

这篇关于使用mod-可能会损失精度(但不是)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆