2016-03-04 120 views
0

稅收取決於他們的工資差距有多大。如果薪水在對方10000美元以內,則稅額爲5%。如果他們相差超過1萬美元,那麼這筆稅是5%的較大收入加上3%的較小收入。 有人可以解釋我做錯了我的if語句是不是讓測試通過。有人可以解釋我的代碼有什麼問題嗎?


public double spouseDistance(double income1, double income2) 
{ 
    double tax; 
    double totalincome = income1 + income2; 
    double incomedistance = income1 - income2; 
    if (incomedistance > 10000) 
    { 
     if(income1 > income2) 
     { 
      tax = income1 * 0.05 + income2 * 0.03; 
     }else 
    { 
     tax = income2 * 0.05 + income1 * 0.03; 
    } 
    } 
     else 
     { 
      tax = totalincome * 0.05; 
     } 

    return tax; 
} 

}


@Test 
public void testSpousesDistance() 
{ 
    TaxCalculator tc = new TaxCalculator(); 
    // The border case here is when the difference between the 
    // salaries is 10,000 and the value changes at 10,000.01. 
    // Since the order of the parameters shouldn't matter, do 
    // both cases with both parameter orders 
    assertEquals(40000*0.05, tc.spouseDistance(25000,15000), 0.001); 
    assertEquals(40000*0.05, tc.spouseDistance(15000,25000), 0.001); 
    assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(20000.00,30000.01), 0.001); 
    assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(30000.01, 20000.00), 0.001); 
} 

}

+0

爲什麼不真正運行代碼並查看返回的「稅」是什麼? – jack3694078

+0

對於下一次遇到這樣的問題時的建議:嘗試使用調試器運行測試,並檢查它是否按照您的預期一步一步地運行。 – Volune

回答

3

你要設置incomeDistanceMath.abs(income1 - income2)得到的差值的絕對值。你的方式,如果income2>income1你分支到錯誤的代碼塊。

以您的20,000和30,000.01爲例。此時incomeDistance變成20,000-30,000.01或-10,000,其中小於10,000。

1

您必須確保收入距離的結果不是負值。因爲如果收入2大於收入1,則在您的代碼中,結果將顯示爲負值。

如果結果是否定的,乘以結果(-1),如果你不 要包括整個圖書館只是一個單一的目的。

相關問題