【问题标题】:percentage of a vector rounding up or down and integer division [duplicate]矢量向上或向下舍入和整数除法的百分比[重复]
【发布时间】: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,因为 noOfExdouble

标签: java


【解决方案1】:

使用Math.round:

double number = 22.5;
int rounded = (int)Math.round(number);

DEMO

【讨论】:

  • 我做了 double noOfEx = Math.round(percentage*set.size()/100);但后来我无法使用 subList,因为我收到一个错误,即没有找到适合 subList(int,double) 的方法。
  • @user4345738 仔细阅读答案。四舍五入的结果是一个 int,您应该使用它而不是 double。
  • @user4345738 您的问题与舍入无关,它与整数除法有关。如果两个操作数都是整数,则结果会自动转换为 int,因此您不会有小数位。请使用double noOfEx = percentage*set.size()/100.0;100.0 的意思是“取100为双”,所以会进行双除。
  • 感谢修复!将更新问题标题
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多