我的代码进退两难,首先我必须编写一个练习来实现以下目标
锻炼
创建一个文件以完成此练习。编写一个程序,生成 100 个随机数(范围为 1-1000),并计算其中有多少是偶数,有多少是奇数。将结果显示在屏幕上,如下面的示例输出所示。提示:使用 while 循环循环 100 次。
我的结果:
import random
num = 0
odd = 0
even = 0
while num < 100:
random.randint(1,1000)
num = num + 1
#print(num)
if random.randint(1,1000)%2==0:
even = even + 1
else:
odd = odd + 1
print ("Out of 100 Random Numbers,",even,"were even and",odd,"were Odd")
输出:
Out of 100 Random Numbers, 50 were even and 50 were Odd
所有肉汁!
下一个活动:
添加另一个 while 循环,该循环将部分 a 重复 10 次。将结果显示在屏幕上,如下面的示例输出所示。
输出如下:
Out of 100 random numbers, 56 were odd, and 44 were even.
Out of 100 random numbers, 60 were odd, and 40 were even.
Out of 100 random numbers, 47 were odd, and 53 were even.
Out of 100 random numbers, 54 were odd, and 46 were even.
Out of 100 random numbers, 48 were odd, and 52 were even.
Out of 100 random numbers, 53 were odd, and 47 were even.
Out of 100 random numbers, 46 were odd, and 54 were even.
Out of 100 random numbers, 52 were odd, and 48 were even.
Out of 100 random numbers, 53 were odd, and 47 were even.
所以我写了:
import random
num = 0
odd = 0
even = 0
loop = 0
while loop < 10:
loop = loop +1
while num < 100:
num = num + 1
rand = random.randint(1,1000)
#print(num)
if rand%2==0:
even = even + 1
else:
odd = odd + 1
result = print ("Out of 100 Random Numbers,",even,"were even and",odd,"were Odd")
导致输出:
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
你们中的一位优秀程序员能否向我解释为什么我会得到这个结果和/或修改代码以获得练习的预期结果。
解释为什么它不起作用以及如何解决它会更好,因为你知道他们说什么,给一个人一条他会吃一天的鱼,教他钓鱼他会吃一辈子。
谢谢你的时间。