2015-06-28 72 views
1

我目前正在通過Python 3.x創建一個三角函數計算器。在我的一個功能中,我爲直角三角形的一個未知角度創建了一個值'angle_b',我通過給它定義函數'ANGLE_B'來定義角度。下面的代碼樹以供參考:TypeError:需要浮點數 - Python

def create(): 
    global side_a 
    side_a = format(random.uniform(1,100),'.0f') 
    global side_b 
    side_b = format(random.uniform(1,100),'.0f') 
    global angle_a 
    angle_a = format(random.uniform(1,180),',.3f') 
    global angle_b 
    angle_b = ANGLE_B() 

def ANGLE_B(): 
    ang = format(math.asin(side_b*(math.sin(angle_a)/side_a)),'.3f') 
    return ang 

我試圖在ANGLE_B()塊轉換成angang = float(ang)然而,我沒有運氣浮點數的多種組合。誰能幫忙?當我在CMD中運行時,我總是收到TypeError: a float is required

+0

我沒有在'ANGLE_B()'中聲明變量'side_b','angle_a'和'side_a',甚至是'global'? –

+1

在'create()'函數中,'side_a','side_b','angle_a'和'angle_b'都被聲明爲全局的並且被定義。它只是'ANGLE_B()'函數定義的'angle_b'變量,所以在這種情況下你的視覺是非常可疑的。 –

+0

我的壞...真的...我的視覺是可疑的...... D –

回答

4

您正在將字符串變量傳遞給math.sin和math.asin,這會導致類型錯誤。您可以通過轉換爲浮動修復:

ang = format(math.asin(float(side_b)* (math.sin(float(angle_a))/float(side_a))),'.3f') 

你也可以只存儲所有這些變量作爲浮動開始。

+0

謝謝你,完美的工作! –

+0

嗨@samgak,我也試過這個,因爲我需要使用ctypes,而且我也有同樣的錯誤,我的代碼是: 'x = 0' 'x = float(x)' 'fp = c_float(x) 'fp = c_float(fp)'感謝您的幫助! –

+1

@AlexanderDeLeonVI問題是最後一條語句'fp = c_float(fp)'。您需要將一個float傳遞給c_float(),但由於'fp = c_float(x)',fp已經是c_float。只要刪除最後的聲明,這是沒有必要的。 – samgak

相關問題