2012-04-19 55 views
1

注意:我正在使用Lua。給定一個圓圈上的兩個點相對於他們的度數,他們之間的度數是多少?

所以,我試圖找出圓上兩點之間的度數。問題是像340和20,其中正確答案是40度,但是做這樣的事情

function FindLeastDegrees(s, f) 
    return ((f - s+ 360) % 360) 
end 

print(FindLeastDegrees(60, 260)) 

-- S = Start, F = Finish (In degrees) 

其中一期工程只是試圖找出兩者之間的距離,當所有的一切情況之間。這下面的代碼是我下一次失敗的嘗試。

function FindLeastDegrees(s, f) 
    local x = 0 
    if math.abs(s-f) <= 180 then 
     x = math.abs(s-f) 
    else 
     x = math.abs(f-s) 
    end 
return x 
end 

print(FindLeastDegrees(60, 260)) 

我然後設法:

function FindLeastDegrees(s, f) 
    s = ((s % 360) >= 0) and (s % 360) or 360 - (s % 360); 
    f = ((f % 360) >= 0) and (f % 360) or 360 - (f % 360); 
    return math.abs(s - f) 
end 

print(FindLeastDegrees(60, 350)) 

--> 290 (Should be 70) 

這樣失敗了。 :/

那麼如何找到兩個其他度數之間的最短度數,然後如果你應該順時針或逆時針(加或減)來到那裏。我完全困惑。

的什麼,我試圖做一些例子...

FindLeastDegrees(60, 350) 
--> 70 

FindLeastDegrees(-360, 10) 
--> 10 

這似乎這麼難!我知道我將不得不使用...

  1. 絕對值?

我也想要它返回,如果我應該增加或減去獲得值'完成'。
對不起,冗長的說明,我想你也許已經知道了....:/

+0

這是鏈接http://stackoverflow.com/questions/16460311/determine-angle-between-two-points-on-a-circle-with-respect-to-center/16460479#16460479 – 2013-05-09 11:40:29

回答

2

如果度都在0至360範圍內,% 360部分可以跳過:

function FindLeastDegrees(s, f) 
    diff = math.abs(f-s) % 360 ; 
    return math.min(360-diff, diff) 
end 
+0

他們不是。然而,我是否可以這樣做: function FindLeastDegrees(s,f) s =((s%360)> = 0)和(s%360)或360-(s%360); (f%360)> = 0)和(f%360)或360-(f%360); 返回math.min(360 math.abs(F-S),math.abs(F-S)) 端 打印(FindLeastDegrees(60,260)) 隨着額外的代碼作爲代碼來獲取度? – Stormswept 2012-04-19 23:15:42

+0

不需要這種併發症。看我的編輯。 – 2012-04-19 23:22:50

+0

啊。我看到你在那裏做了什麼!謝謝! – Stormswept 2012-04-19 23:46:52

相關問題