2011-09-11 350 views
0

我有方法,它有2個整數作爲參數並返回:簡單方程失敗單元測試

public int method(int a, int b){ 
    return Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10) 
} 

我已經創建單元測試,這通過爲值1400和1500(預期值是43),但是它沒有爲1459年和1500年。預期的輸出是18,但我的方法返回17. 我相信這可能與舍入有關,但我看不到任何明顯的錯誤。不應該有與舍入任何問題17.7(6)18

編輯:

的真正功能是略低不同(我沒有Math.abs(AB),而是我已經定義的「差異」 。變量作爲這樣的結果,我可以向你保證,我宣佈它爲雙差異傢伙; - 我不知道爲什麼它成爲INT差異:)解決謝謝:)

回答

4

Math.absMath.min通過int時都返回int小號s作爲參數,所以你的代碼正在做整數除法,而不是你所期望的雙重除法。如果您將310替換爲3.010.0,則代碼應按預期工作。

1

在使用整數除法時期望加倍是本書中最古老的問題。 ;)

你的回合不會做任何事情,因爲你的整數除法產生整數結果。

2

這是因爲它正在執行整數除法。與a = 1459b = 1500

Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10) 
Math.round(Math.abs(41)/3 - (1459-1500)/10) 
Math.round(41/3 - (-41)/10) 
Math.round(13 - (-4)) 
Math.round(17)  // note that round will always get an integer as input 
17 

的簡單的解決方法是通過代替使用浮動作爲參數之一來強制它執行浮點除法:

Math.round((Math.abs(a-b)/3.0) - (Math.min(a,b)-1500)/10.0) 
0

預期的結果是17。

|a-b| = 41 
|a-b|/3 = 13 

min(a,b) = 1459 
min(a,b)-1500 = -41 
(min(a,b)-1500)/10 = -4 

13-(-4) = 17 

我懷疑你不想有整數除法。因此,您必須用3.010.0替換310

0

你必須記住要考慮到一個事實,即當一個整數除以Java中的另一個整數時,結果是一個整數,而不是一個浮點數(任何餘數被丟棄)。例如6/4 == 1,而不是1.5

方法(1459,1500)

Math.round((Math.abs(1459-1500)/3) - (Math.min(1459,1500)-1500)/10); 
Math.round((41/3) - (1459-1500)/10); 
Math.round(13 - (-41)/10); //41/3 == 13, not 13.6666 
Math.round(13 - -4); //-41/10 == -4, not -4.1 
Math.round(17); 
17