简体   繁体   English

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

[英]Problem with Automated Testing & Wrong Formula

Im in an intro to java programming course and we're doing a project in Bluej where we need to use automated testing to run our code.我正在介绍 java 编程课程,我们正在 Bluej 中做一个项目,我们需要使用自动化测试来运行我们的代码。 The test code is given and cannot be changed, and we have to write code and run the tests successfully.测试代码是给定的,不能更改,我们必须编写代码并成功运行测试。 Mine is all running smoothly except for this last part.除了最后一部分外,我的一切运行顺利。 Here is a snippet from the test code:以下是测试代码的片段:

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

And here is the method I wrote for it.这是我为它写的方法。 It compiles but when I run it through the test I get a failed error that says "expected:<160> but was:<180>" I thought I had the formula correct but I guess not.它可以编译,但是当我通过测试运行它时,我得到一个失败的错误,上面写着“预期:<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;
    }

I'm not sure what I'm doing wrong here.我不确定我在这里做错了什么。 Any insight would be awesome.任何见解都会很棒。 Thanks in advance!提前致谢!

You are subtracting givenPercentage as an absolute number.您正在减去givenPercentage作为绝对数。 What you are looking for is to subtract percentage of population.您正在寻找的是减去人口百分比。 20% of 200 is 40. 200-40=160. 200 的 20% 是 40。200-40=160。 Correct code:正确代码:

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