繁体   English   中英

自动测试和错误公式的问题

[英]Problem with Automated Testing & Wrong Formula

我正在介绍 java 编程课程,我们正在 Bluej 中做一个项目,我们需要使用自动化测试来运行我们的代码。 测试代码是给定的,不能更改,我们必须编写代码并成功运行测试。 除了最后一部分外,我的一切运行顺利。 以下是测试代码的片段:

    public void test_spray() {
        int currentRoaches = population.getRoaches();
        population.spray(20);     // reduce the population by 20%
        assertEquals((int)(currentRoaches * 0.80), population.getRoaches() );
    }

这是我为它写的方法。 它可以编译,但是当我通过测试运行它时,我得到一个失败的错误,上面写着“预期:<160> 但是:<180>”我以为我的公式是正确的,但我猜不是。

 /* simulates spraying with insecticide, which reduces the population
    by the given percentage. */ 
    public void spray(double givenPercentage) {
        this.population = this.population - (int)givenPercentage;
    }

我不确定我在这里做错了什么。 任何见解都会很棒。 提前致谢!

您正在减去givenPercentage作为绝对数。 您正在寻找的是减去人口百分比。 200 的 20% 是 40。200-40=160。 正确代码:

public void spray(double givenPercentage) {
    this.population = this.population - (int)((givenPercentage/100) * this.population);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM