2017-02-12 79 views
0

我想在C中做一個函數,它使用餘弦定律返回與給定角度相反的三角形邊的長度。編寫一個餘弦定律計算

現在我得到了在Excel中工作的公式,它給出了正確的結果。然而,當我在C中嘗試它時,我得到了錯誤的結果,並且我無法弄清楚爲什麼。

對於測試,我有sideA爲21.1,sideB爲19,它們之間的角度爲40度。現在答案應該是14.9,就像我在Excel中獲得的一樣。然而在C中我得到了23.735。請有人幫我找出我出錯的地方

// Find the length of a side of a triangle that is oppisit a given angle using the Law Of Cosine 
// for example using an triangle that is 21.1cm on one side, 19 cm on the other and an angle of 40 degreese inbetween then.... 
// in excel it worked and the formuler was =SQRT(POWER(23.1;2)+POWER(19;2)-2*(23.1)*(19)*COS(40*(3.14159/180))) = 14.9 cm 
float my_Trig_LawOfCos_OppSideLength(float centerAngle, float sideA, float sideB) 
    { 
     float sideLengthPow2= (pow(sideA,2) + pow(sideB,2))) - ((2*sideA*sideB)*cos(centerAngle*(3.14159/180)); 
     float sideLength = sqrt(sideLengthPow2); 
     return sideLength; 
    } 
+2

你的括號不平衡(當我複製粘貼你的示例時,我的編譯器只是抱怨)。所以我不相信這是你的實際代碼。 – StoryTeller

+0

[當我修復*問題時,我得到了您期望的結果](http://ideone.com/Gd4oqO)。 – StoryTeller

+0

注意,如果代碼使用'float',不妨使用'float'函數:'sqrtf()','cosf()'等 – chux

回答

2

如果按錯誤順序傳遞參數,會發生這種情況。您將邊長23.1置於角度的位置。

def oppside(ang, lA, lB): return (lA**2+lB**2-2*(lA)*(lB)*cos(ang*(pi/180)))**0.5 

oppside(40,19,23.1) 
>>> 14.905575729577208 

oppside(19,23.1,40) 
>>> 19.65430416708927 

oppside(23.1,19,40) 
>>> 23.72490935854042 

很多時候,您可以找到產生最小的可執行文件的例子,顯示錯誤的結果這樣的錯誤,因爲那樣的話你也記錄了錯誤的函數調用(甚至看到它自己)。