【发布时间】:2015-03-01 12:21:51
【问题描述】:
我有以下代码来获取“set”的百分比,例如,如果输入 60%,它只保留 9 个“set”示例。但是,我需要将其修改为 >0.5 我将数字向上舍入,但如果它是
public void proportion(int percentage)
{
int noOfEx = percentage*set.size()/100;
root.keptEx = new Vector(set.subList(0, noOfEx));
}
我试过了
public void proportion(int percentage)
{
double noOfEx = percentage*set.size()/100;
int rounded = (int)Math.round(noOfEx);
root.keptEx = new Vector(set.subList(0, rounded));
System.out.println(noOfEx);
}
但如果 set.size 是 16,我仍然会得到 9,而我需要 10
【问题讨论】:
-
是的,但我需要同时向上和向下舍入
-
首先,为 noOfEx 使用双精度:
double noOfEx = percentage*set.size()/100.0;然后,使用 Math.round() 进行所需的舍入:root.keptEx = new Vector(set.subList(0, Math.round(noOfEx)); -
@DannyDaglas
Math.round(noOfEx)需要转换为int,因为noOfEx是double
标签: java