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

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

任何帮助将不胜感激!

最佳答案

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

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

关于java - 通过按给定百分比增加来传递和更新分数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830321/

相关文章:

java - 用全大写、小写和反向java将字符串打印到文件中

java - IDL corba 中的数组和对象错误

c - 如何检查整数是否已排序(两侧)

sql-server - 如何在 SQL Server 中加密函数

java - 为什么SpringApplication通过配置加载ApplicationContextInitializer?

java - ASM 4.1访问LdcInsn常量池中的非法类型

arrays - 从数组中添加哈希

C 传递数组的大小

java - 将开始点和停止点参数添加到将字符串中的数字之和相加的方法

java - 从双数组计算统计信息