两个int的乘法变为负数 [英] Multiplication of two int's gets negative
问题描述
我正在编写一个小的下载管理器,当我尝试以百分比计算下载进度时,我得到一个有趣的输出。这是我用来计算它的:
I'm currently coding a little download manager and I get a funny output when I try to calculate the download-progress in percent. This is what i use to calculate it:
int progress = (byte_counter * 100) / size;
System.out.println("("+byte_counter+" * 100) = "+(byte_counter * 100)
+" / "+size+" = "+progress);
字节计数器
是一个int(它计算从 InputStream
中读取的总字节数, size
是下载文件的长度(以字节为单位)。
byte-counter
is an int (it counts the total bytes read from the InputStream
) and size
is the length of the downloaded file in bytes.
这适用于小型下载。但是当我获得更大的文件(40MB)时,它开始制作有趣的东西。计算的输出如下所示:
This works great with small downloads. But when i get to bigger files (40MB) it starts making funny things. The Output for the calculation looks like this:
[...]
(21473280 * 100) = 2147328000 / 47659008 = 45
(21474720 * 100) = 2147472000 / 47659008 = 45
(21476160 * 100) = -2147351296 / 47659008 = -45
(21477600 * 100) = -2147207296 / 47659008 = -45
[...]
我不知道为什么,但计算变得消极。 因为正常的整数应该没有数字,直到2 31 -1,这不应该是问题根。但是我错过了什么?
I don't know why, but the calculation gets negative. Since an normal Integer should be fine with numbers till 231-1, this shouldn't be the problems root. But what am I missing?
推荐答案
请参阅 http:// en .wikipedia.org / wiki / Arithmetic_overflow
要修复java,请尝试使用 long
代替。
To fix in java, try using a long
instead.
int progress = (int) ((byte_counter * 100L) / size);
或相反的操作顺序
int progress = (int) (((float) byte_counter) / size) * 100);
这篇关于两个int的乘法变为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!