2015-01-03 55 views
-1

我有以下代碼來取'set'的百分比,例如如果輸入60%,它只保留9個'set'的例子。但是,我需要修改這個,就好像> 0.5我將數字加起來,但如果它是< 0.5我將其舍入。比如9.6保留前10個訓練樣例而9.4保留前9個例子。矢量向上舍入或向下舍入的百分比和整數除法

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

+0

https:// www.google.co.uk/webhp?#q=java%20round%20to%20the%20nearest%20integer – NPE

+0

是的,但我需要同時上下調整 – user4345738

+1

首先,對noOfEx使用雙精度型:'double noOfEx =%* set.size()/ 100.0;'然後,使用Math.round()做你想要的四捨五入:'root.keptEx = new Vector(set.subList(0,Math.round(noOfEx)) ;' –

回答

0

使用Math.round

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

DEMO

+0

我做了雙倍noOfEx = Math.round(百分比* set.size()/ 100 );但後來我不能使用subList,因爲我收到一個錯誤,沒有找到合適的方法subList(int,double)。 – user4345738

+0

@ user4345738仔細閱讀答案。四捨五入的結果是一個int,你應該使用它來代替double。 – BackSlash

+0

請參閱更新 – user4345738