Java divison与两个整数操作数不起作用? [英] Java divison with two integer operands not working?

查看:64
本文介绍了Java divison与两个整数操作数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我的数学运算仅返回0.已检查了该值.

For some reason my math just returns 0. The value are set, I have checked.

int currentSize = 4079;
int totalSize = 500802;

int percentage = ((currentSize/totalSize) * 100);
progdialog.setProgress(percentage);

百分比始终等于百分比. 为什么?

Percentage always equals percentage. Why?

推荐答案

正如其他人指出的那样,问题是整数除法会将小于1的值变为零.这发生在乘以100之前.您可以更改操作顺序以获得更好的效果:

The problem, as other have pointed out, is integer division will turn anything less than 1 to zero. This happens before multiplying by 100. You can change the order of operations to get something better:

int percentage = currentSize * 100 / totalSize;

如果您担心舍入,可以使用

If you are concerned about rounding, you can use

int percentage = (currentSize * 100 + (totalSize >> 1)) / totalSize;

这避免了使用double或float值的花费.

These avoid the expense of working with double or float values.

这篇关于Java divison与两个整数操作数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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