[英]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.