以下是具体问题: 使用函数编写程序以生成许多随机数并确定:
1.生成正值的数量,
2.零值的数量,
3.生成的负值数量
4.平均值为浮点数到一位十进制数
到目前为止,我已经能够生成随机数,而且就此而言
import random
def randomNum (x):
counter = 0
zerocounter = 0
while counter <= x:
t = random.randint(-x,x)
if t == 0:
zerocounter = zerocounter + 1
a = t/x
print(t)
average = average + a
counter = counter + 1
return average,zerocounter
number = int(input("input max range of numbers "))
average,zerocounter = randomNum(number)
print(average)
print(zerocounter)
我已经想出如何计算零和平均值我只需要整数和负数的帮助
答案 0 :(得分:0)
这是一个代码演示:
In [59]: number = int(input("input max range of numbers: "))
...: howmany = int(input("how many numbers to generate: ")) #use another variable
...: rand_nums=[random.randint(-number, number) for i in range(howmany)]
...: #pos_cnt=sum(1 for i in rand_nums if i>0) #one liner to count the postive ints inside the list.
#Otherwise use a loop as below
...: pos_cnt=neg_cnt=zero_cnt=0 #use 3 separate counters
...: for i in rand_nums:
...: if i>0:
...: pos_cnt+=1
...: elif i==0:
...: zero_cnt+=1
...: else:
...: neg_cnt+=1
...: print(rand_nums)
...: print('there are {} postive ints, {} zeros, {} negative ints'.format(pos_cnt, zero_cnt, neg_cnt))
...: print('list mean is:', 1.0*sum(rand_nums)/len(rand_nums))
#sample input & output:
input max range of numbers: 111
how many numbers to generate: 11
[4, -44, -88, 103, 34, 82, 17, 93, 107, -98, 93]
there are 8 postive ints, 0 zeros, 3 negative ints
list mean is: 27.545454545454547