今天写了一个Python的多线程求和程序。满足以下要求:
1、可以设置步长
2、步长可为负
3、支持小数
4、可指定线程数
5、处理各种无效输入
程序如下:
import threading
from math import ceil
result = 0
def sub_sum(start, end, step):
global result
sum = float(0)
temp = start
while temp < end + step / 1000000:
sum += temp
temp += step
#print("sum from %f to %f by the step %f is %f"\
# % (start, end, step, sum))
result += sum
def thread_sum(start, end, step = 1, num_thread = 1):
global result
num_threads = int(num_thread)
if (num_threads <= 0):
num_threads = 1
end = start + int((end - start)/step) * step
numbers = end - start
if (numbers < 0 and step > 0) or (numbers > 0 and step < 0):
print("error in sum: from %f to %f by the step %f is i