2017-06-23 45 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()实际上会提供与您的代码相同的效率。如果你想缩短代码或者看起来更具可读性,你可以使用它们。

相关问题