2014-05-01 29 views
0

基本問題,但我似乎無法環繞它我的頭:停止後的若干在一定的範圍內

我有東西旋轉,我想在一定的範圍內,以阻止它。

所以我希望它返回false如果旋轉(這是雙)在一定範圍內。

旋轉= 182,STOPAT 180,精度2。因此,應停止。

Rotation = 182,StopAt 180,Accuracy 1.所以不應該停下來。

目前我有:

/** 
* 
* @return 
* number = 100, current = 105, accuracy = 10 
* Example 
* 105c/100n = 1.05.. 
* 10c/100n = 0.1.. 
*/ 
public boolean stopAtRange(double number, double current, double accuracy) 
{ 
    if(current/number) + accuracy) 
    { 
     return true; 
    } 
    return false; 
} 
+0

你在這裏做什麼:'if(current/number)+ accuracy)'? – bytefire

+0

'if'要求'boolean'值,而不是'double'。像'if(a + b> 0)'是正確的,但是'if(a + b)'不正確。 – Pshemo

+0

您發佈的代碼甚至無法編譯。 精度範圍是百分比還是絕對精度? – David

回答

4

在Java中if只取布爾值,整數值不轉換爲布爾值。

達到你想要什麼,你的方法應該是這樣的

public boolean stopAtRange(double number, double current, double accuracy) 
{ 
    if(Math.abs(current - number) <= accuracy) 
    { 
     return true; 
    } 
    return false; 
} 

這項工作如果兩者是current大於或小於number較小。如果你只是想停止,如果current較大或至少等於number,比你應該刪除Math.abs

我也建議使用此版本:

public static boolean stopAtRange(double number, double current, double accuracy) { 
    return Math.abs(current - number) <= accuracy; 
} 

,因爲它更緊湊,並進行了優化,表演也是如此。

1

下面將停止,如果currentnumber +/- accuracy遠:

public boolean stopAtRange(double number, double current, double accuracy) 
{ 
    if(Math.abs(current - number) <= accuracy) 
    { 
     return true; 
    } 
    return false; 
} 
0

如果接受一個布爾值,而不是雙。類似於:

public boolean stopAtRange(double number, double current, double accuracy) 
{ 
    if(Math.abs(current-number) <= accuracy) 
    { 
     return true; 
    } 
    return false; 
} 
1

您的問題有點令人困惑,但我會盡我所能提供幫助。 :)

此代碼不能編譯:

if(current/number) + accuracy) 

首先,你已經打開了一個支架,然後關閉了兩家。你會想:

if((current/number) + accuracy) 

其次,這將不計算爲一個布爾值(true或false),這是必要的你的if語句工作。你想:

public boolean stopAtRange(double number, double current, double accuracy) 
{ 
    if(Math.abs(current - number) <= accuracy) return true; 
    return false; 
} 

這工作了你的號碼(100 & 105)之間的差值,如果他們的範圍(10)內確認。

希望這會有所幫助!