我有这个随机数生成器来记录随机生成器记录的正,负和零。但是,当我测试它时,负数不会记录,而是记录在正计数器中。我没有看到我的代码有什么问题,有什么帮助吗?
from random import randint
posi_counter = 0
nega_counter = 0
zero_counter = 0
avg_counter = 0
# Inputs
num_gen = int(input("How many numbers to be generated? "))
if num_gen > 0:
max_gen = int(input("Enter maximum number to be generated (>0): "))
min_gen = max_gen * -1
print("For {} numbers in the range, {} to {}:".format(
num_gen, min_gen, max_gen))
avg = 0
# Outputs
for x in range(num_gen):
print(randint(min_gen, max_gen))
avg_counter += 1
avg = avg + x
if x > 0:
posi_counter += 1
elif x < 0:
nega_counter += 1
elif x == 0:
zero_counter += 1
average_total = avg / avg_counter
print("{} positive numbers".format(posi_counter))
print("{} zero numbers".format(zero_counter))
print("{} negative numbers".format(nega_counter))
print("{:.1f} average value".format(average_total))
答案 0 :(得分:3)
x
来自range(num_gen)
,因此始终为>= 0
,请执行以下操作:
for _ in range(num_gen):
x = randint(min_gen, max_gen)
print(x)