2017-06-23 44 views
1

我想測試一個變量是否在兩個其他變量之間,如果這個不清楚看我的代碼。這段代碼的工作原理,我只是尋找一個更短,更有效的方式來執行相同的事情。給定兩個變量,測試其他變量是否在它們之間

public boolean isBetween(double test, double n1, double n2){ 
     double lowN = n1 < n2 ? n1 : n2; 
     double highN = n1 > n2 ? n1 : n2; 
     if(n1 == n2 && test == n1){ 
      return true; 
     } 
     if(test >= lowN && test <= highN){ 
      return true; 
     } 
     return false; 
    } 

目前,我使用兩個三元運營商可以定義哪些變量是低和高,然後我看到測試變量是否是他們之間

+1

'return test> = Math.min(n1,n2)&& test <= Math.max(n1,n2);' – shmosel

+0

話雖如此,這是無關緊要的。它屬於http://codereview.stackexchange.com - 這就是爲什麼我沒有提交答案。 –

+1

這是一個更優雅更直觀的解決方案(如果您不想使用'Math.min'和'Math.max')。 - 'return test> = n1 && test <= n2 || test> = n2 && test <= n1;' –

回答

5

您可以使用Math.max()Math.min()

private static boolean isBetween(double test, double d1, double d2) { 
    return test >= Math.min(d1, d2) && test <= Math.max(d1, d2); 
} 
1

替代解決方案:

public boolean isBetween(double test, double n1, double n2) { 
    return n1 > test ? n2 > test && n2 < n1 : n2 > n1 && n2 < test; 
} 

表示我其實更喜歡其他解決方案,更具可讀性;指的是使用Math.min()和Math.max()

1

這部分甚至不需要。它也應該沒有它。

if(n1 == n2 && test == n1){ 
     return true; 
    } 

另外使用Math.min()和Math.max()實際上會提供與您的代碼相同的效率。如果你想縮短代碼或者看起來更具可讀性,你可以使用它們。

相關問題