计算百分比时,Java中存在奇怪的除法错误

时间:2013-10-07 10:27:51

标签: java

在尝试计算某些百分比时,我得到了一些奇怪的结果。如果我的值为1,最大值为2,那么我应该得到50%的结果(因为1是2的50%),但是我得到1%的结果。这是我的代码:

int percent = ( runningMins / goal.getGoalMins() )  * 100;
System.out.println(runningMins +", " + goal.getGoalMins() + ", progress: " + percent);

当runningMins = 1且goal.getMins = 1时的结果:

1, 1, progress: 100

当runningMins = 1且goal.getMins = 2时的结果:

1, 2, progress: 1

runningMins = 1和goal.getMins = 4:

1, 4, progress: 1

runningMins = 1和goal.getMins = 8:

1, 8, progress: 1

我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

你可以尝试:

int percent = ( (float)runningMins / goal.getGoalMins() )  * 100;

或更好

int percent = ( 100 * runningMins ) / goal.getGoalMins()

因为除非整数不能给出其他东西,所以0或1 ......

答案 1 :(得分:0)

 int percent = ( (float)(runningMins /goal.getGoalMins()) )  * 100;

Java arithmetics for calculating a percentage

答案 2 :(得分:0)

试试这种方式

float percent = ( runningMins /(float) goal.getGoalMins() )  * 100;