Java 向量上下舍入和整数除法的百分比
我有下面的代码来表示“set”的百分比,例如,如果输入60%,则只保留“set”的9个示例。但是,我需要修改它,就像我将数字向上舍入>0.5一样,但如果它是则使用Java 向量上下舍入和整数除法的百分比,java,Java,我有下面的代码来表示“set”的百分比,例如,如果输入60%,则只保留“set”的9个示例。但是,我需要修改它,就像我将数字向上舍入>0.5一样,但如果它是则使用Math.round: double number = 22.5; int rounded = (int)Math.round(number); 是的,但我需要同时上下取整。首先,对noOfEx使用double:double noOfEx=percentage*set.size()/100.0然后,使用Math.round()进行所需
Math.round
:
double number = 22.5;
int rounded = (int)Math.round(number);
是的,但我需要同时上下取整。首先,对noOfEx使用double:
double noOfEx=percentage*set.size()/100.0
然后,使用Math.round()进行所需的舍入:root.keptEx=new Vector(set.subList(0,Math.round(noOfEx));
@DannyDaglasMath.round(noOfEx)
需要转换为int
,因为noOfEx
是一个double
我做了double noOfEx=Math.round(percentage*set.size()/100);但是我不能使用subList,因为我得到一个错误,没有为subList找到合适的方法(int,double)@user4345738仔细阅读答案。取整后的结果是一个整数,您应该使用它而不是双精度。@user4345738您的问题与取整无关,而是与整数除法有关。如果两个操作数都是整数,则结果将自动转换为整数,因此您将没有小数位数。请使用double noOfEx=percentage*集。size()
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);
}
double number = 22.5;
int rounded = (int)Math.round(number);