抛硬币实验为什么大于100次仍然有显示
import randomcounts = int(input("请输入抛硬币的次数:"))
i = 0
z=0
f=0
print("开始抛硬币实验:")
if i<=100:
while i < counts:
num = random.randint(1, 10)
if num % 2:
print("正面", end=" ")
z+=1
else:
print("反面", end=" ")
f+=1
i += 1
else:
while i < counts:
num = random.randint(1, 10)
if num % 2:
z+=1
else:
f+=1
i += 1
print("正面反面分别是"z,f)
因为你是用 i 与 100 比较,i 的初始值为 0,所以 if i <= 100 肯定是满足条件的,
你应该把 i 改为 counts:
import random
counts = int(input("请输入抛硬币的次数:"))
i = 0
z=0
f=0
print("开始抛硬币实验:")
if counts<=100: # 注意这里
while i < counts:
num = random.randint(1, 10)
if num % 2:
print("正面", end=" ")
z+=1
else:
print("反面", end=" ")
f+=1
i += 1
else:
while i < counts:
num = random.randint(1, 10)
if num % 2:
z+=1
else:
f+=1
i += 1
print("正面反面分别是", z,f) isdkz 发表于 2022-3-11 21:09
因为你是用 i 与 100 比较,i 的初始值为 0,所以 if i
谢谢哈\(^o^)/~
页:
[1]