通过增加给定百分比来传递和更新分数数组

时间:2017-03-16 09:42:55

标签: java arrays function percentage

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%)的数组,但不是每个项目更新给定的百分比,它似乎除了数组内的项目之间的百分比,给我丑陋的数字。

任何帮助都会有很大的帮助!

2 个答案:

答案 0 :(得分:1)

为什么要更改循环中百分比的值? 我会这样做:

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

答案 1 :(得分: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);
        }

    }