我目前正在编写一个小下载管理器,当我尝试以百分比计算下载进度时,我得到了一个有趣的输出。这就是我用来计算的:
int progress = (byte_counter * 100) / size;
System.out.println("("+byte_counter+" * 100) = "+(byte_counter * 100)
+" / "+size+" = "+progress);
byte-counter
是一个 int (它计算从InputStream
) and size
是下载文件的长度(以字节为单位)。
这对于小下载量非常有效。但是当我处理更大的文件(40MB)时,它开始产生有趣的事情。计算的输出如下所示:
[...]
(21473280 * 100) = 2147328000 / 47659008 = 45
(21474720 * 100) = 2147472000 / 47659008 = 45
(21476160 * 100) = -2147351296 / 47659008 = -45
(21477600 * 100) = -2147207296 / 47659008 = -45
[...]
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?
See http://en.wikipedia.org/wiki/Arithmetic_overflow
要在 java 中修复,请尝试使用long
反而。
int progress = (int) ((byte_counter * 100L) / size);
或相反的操作顺序
int progress = (int) (((float) byte_counter) / size) * 100);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)