2017-03-16 22 views
0
public class ScoreCard { 

private double[] scores; 
/** 
* 
* @param val 
* @param low 
* @param high 
* @return low if val < low, 
* high if val > high, 
* val if val is between low and high 
*/ 
private double constrain(double val, int low, int high) { 
    if (val < low) 
     return low; 
    if (val > high) 
     return high; 
    return val; 
    } 

. 
. 
. 
. 

/** 
* update each score so it increases by given percentage. For example, 
* if score = {60.0, 90.0} before the method is called, it should 
* become {72.0, 100.0} after the method is called with parameter 20. 
* Note: 90.0 increased by 20% is 108, but scores should be constrained between 
* 0 and 100. So, 100. 
* @param percentage 
*/ 

public void scale(double percentage) { 
    for (int i = 0; i < scores.length; i++) { 
     percentage = scores[i]/100.0 * percentage; 
     scores[i] += constrain(percentage, 0, 100); 
     } 
    } 

我一直被困在一個項目的一小段代碼上。當我嘗試並傳遞此函數時,我失敗了JUnit測試。它似乎正確地更新數組與給定的百分比(10%),而不是每個項目更新由給定的百分比,它似乎劃分數組內的項目之間的百分比,給我醜陋的數字。通過以給定百分比增加來傳遞和更新分數陣列

任何援助將大大appreicated!

+1

如果你想單獨更新每個分數,你爲什麼有獲取每個分數增加一個'sum'變量(由以前的總和)? – UnholySheep

+0

constrain()在代碼中的作用 –

+0

如果'sum == 0',我在代碼 – copernicon1543

回答

1

你爲什麼要改變循環中的百分比值? 我會做一些像這樣:

for (int i = 0; i < scores.length; i++) { 
    scores[i] = constrain(scores[i]*(1+percentage/100), 0, 100); 
} 
+0

所以我的邏輯百分比不斷更新循環? – copernicon1543

+0

@ copernicon1543是.................... –

0
public void scale(double percentage) { 
    for (int i = 0; i < scores.length; i++) { 
     percentage = scores[i]/100.0 * percentage; 

     scores[i] =(scores[i]+percentage)>=100?100:(scores[i]+percentage); 
     } 

    } 
+1

只是沒有解釋的代碼不被認爲是一個好的答案。另外未使用的變量'double sum = 0;'的目的是什麼? – UnholySheep

+0

@UnholySheep在我改變它之前,「sum」變量是舊代碼,我的錯誤。你對自己的邏輯提出質疑是正確的。 – copernicon1543

+0

感謝你們所有的幫助,好像我現在已經通過了Junits。 – copernicon1543