2013-11-25 81 views
-5

它提示我這個錯誤的圖像: 我不知道是否有人能弄明白什麼是錯我的代碼,我會理解 錯誤:爲什麼會發生這種情況?

Unhandled exception in thread started by 0.06<function su at 0x00000000032E4620> 

Traceback (most recent call last): 
    File "C:\Users\Zryan\Downloads\z.py", line 6, in su 
    for index in range(st,end+i): 
TypeError: 'float' object cannot be interpreted as an integer 

代碼:

import random 
import _thread 
def su(st,end,i): 
    global subtotal, data, locks 
    locks.acquire(1,-1) 
    for index in range(st,end+i): 
     subtotal[i] += data[index] 
    locks.release() 

numth = int(100) 

data = list(range(numth)) 

for index in range(len(data)): 
    data[index] = random.randint(1,10) 

wt=int(input("enter the number of working threads:")) 

locks = list(range(wt)) 

subtotal = list(range(wt)) 

seg = len(data)/wt 

st=0 
locks= _thread.allocate_lock() 
for i in range(wt): 
    st= i * seg 
    end = st *seg -1 
    _thread.start_new_thread(su,(st,end,i)) 
avg = sum(subtotal)/len(data) 

print(avg) 
+3

請不要轉發你的問題稍作修改。 – Hyperboreus

+2

這個問題似乎是脫離主題,因爲它是一個轉發。 – Hyperboreus

+0

你是回答先生還是什麼? –

回答

1

在將len(data)除以wt(我假設您使用的是Python 3)之後,seg的值可能是浮點值。這也會使end成爲一個浮點值,當您嘗試將end作爲參數傳遞給range時,會導致觀察到的錯誤。

您需要確保end是一個整數;最簡單的方法是在設置其值時簡單使用int(seg)而不是seg

+0

Aha現在我明白了 –

相關問題