天天看點

Python 錯誤提示not supported between instances of ‘complex‘ and ‘int‘

File “c:\Users\Administrator\app.py”, line 13, in

if disDigit <= r1 and r2 <= r1:

TypeError: ‘<=’ not supported between instances of ‘complex’ and ‘int’

當我今天看到這個提示的時候腦子裡一片混亂。

現在分析一下這個問題的由來。

首先請忽略我下方這個計算圓與圓之間距離的程式

x1, y1, r1 = eval(

input("Enter circle1’s center x-,y-coordinates, and radius: "))

x2, y2, r2 = eval(

input("Enter circle2’s center x-,y-coordinates, and radius: "))

disDigit = (pow((x2-x1), 2) + pow((y2-y1), 2)) ** 0.5

if disDigit <= r1 and r2 <= r1:

print(“circle2 is inside circle1”)

elif disDigit >= r1 and r2 <= r1:

print(“circle2 does not overlap circle1”)

當我輸入了x1,y1,r1 = 0.5,5.1,13

x2,y2,r2 = 1,1.7,4.5

結果系統就出現了開頭的提示。

這個是為什麼呢??

後來我發現是不是和disDigit這個變量有關呢

我采用了有效的列印功能

disDigit = (pow((x2-x1), 2) + pow((y2-y1), 2)) ** 0.5

print(disDigit) 在此處我加了一個print,真的這個功能真的很适合調試。

我發現結果竟然是(2.05926462249911e-16+3.363034344160047j)

天哪真的太離譜了

原來我的公式寫錯了應該是下面這個樣子是相減的

disDigit = (pow((x2-x1), 2) - pow((y2-y1), 2)) ** 0.5

好了修改完後運作正常再次輸入剛才的數值

disDigit = 3.4365680554879163

而結果是

circle2 is inside circle1

是以這個小問題也許不是問題。希望對大家有所幫助