它提示我图像中出现此错误: 我想知道是否有人能够弄明白我的代码有什么问题,我将不胜感激 错误:
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)
答案 0 :(得分:1)
将seg
除以len(data)
(我假设您使用的是Python 3)后,wt
的值可能是浮点值。这会使end
成为浮点值,当您尝试将end
作为参数传递给range
时,会导致观察到的错误。
您需要确保end
是一个整数;最简单的方法是在设置其值时简单地使用int(seg)
而不是seg
。