关于抛硬币实验,要求出连续正面和连续反面的次数
下面是我写的代码,能跑起来,但是连续正面和连续反面的次数总是不对,求教是什么原因?-----------------------------------------------------------------------------------------------
import random
number = int(input("请输入抛硬币的次数:"))
while True:
i = 0
sum1 = 0
sum2 = 0
last = 0
c_head = 0
c_tail = 0
max_head = 0
max_tail = 0
print("开始抛硬币实验......")
while i < number:
a = random.randint(1,10)
if a % 2 == 0:
sum1 += 1
c_head += 1
if number < 100:
print("正面",end = " ")
if c_head >= max_head:
max_head = c_head
if last == 2:
c_head = 1
last = 1
if a % 2 != 0:
sum2 += 1
c_tail += 1
if number < 100:
print("反面",end = " ")
if c_tail >= max_tail:
max_tail = c_tail
if last == 1:
c_tail = 1
last = 2
i += 1
print("一共模拟了",sum1 + sum2,"次抛硬币,结果如下:","\n正面:",sum1,"\n反面:",sum2)
print("最多连续正面:",max_head,"次")
print("最多连续反面:",max_tail,"次")
number = int(input("\n请输入抛硬币的次数:"))
先判断if last == 2:
c_head = 1
然后再 c_head += 1
不然明明上次是背面,你却c_head再加1,导致最后c_head最大值--》反面---》c-head增加1--》c-head以比最大值大1的数值赋值给max_head,然后你才把c_head变成1.最终导致max_head比最大值大1.
反面同理
另外你最上边的while循环没有设置break语句,导致整个代码一直循环,停住也只是因为等待你输入。最好最后设置一下break结束循环
import random
number = int(input("请输入抛硬币的次数:"))
while True:
i = 0
sum1 = 0
sum2 = 0
last = 0
c_head = 0
c_tail = 0
max_head = 0
max_tail = 0
print("开始抛硬币实验......")
while i < number:
a = random.randint(1,10)
if a % 2 == 0:
if last == 2:
c_head = 1
sum1 += 1
c_head += 1
if number < 100:
print("正面",end = " ")
if c_head >= max_head:
max_head = c_head
last = 1
if a % 2 != 0:
if last == 1:
c_tail = 1
sum2 += 1
c_tail += 1
if number < 100:
print("反面",end = " ")
if c_tail >= max_tail:
max_tail = c_tail
last = 2
i += 1
print("一共模拟了",sum1 + sum2,"次抛硬币,结果如下:","\n正面:",sum1,"\n反面:",sum2)
print("最多连续正面:",max_head,"次")
print("最多连续反面:",max_tail,"次")
s=input('还继续吗(Y/N):')
if s == 'Y':
number = int(input("\n请输入抛硬币的次数:"))
else:
break 本帖最后由 jackz007 于 2020-12-15 16:24 编辑
import random
maxa , maxb = 0 , 0
number = int(input("请输入抛硬币的次数:"))
print("开始抛硬币实验......")
# 由于正反面计数需要连续,为了避免循环中的条件判断过于复杂,
# 在循环开始前,先抛一次开个头,循环中的判断条件就单一化了。
x = random . randint(1,10)
if x % 2:
a , b = 1 , 0
else:
a , b = 0 , 1
for _ in range(number - 1):
x = random . randint(1,10)
if x % 2:
if a :
a += 1
else:
if b > maxb:
maxb = b
a , b = 1 , 0
else:
if b:
b += 1
else:
if a > maxa:
maxa = a
a , b = 0 , 1
print("最多连续正面:", maxa ,"次")
print("最多连续反面:", maxb ,"次")
# 导入随机模块 #
import random
# 接收用户输入并将数值赋值给 counts 变量 #
counts=int(input("请输入抛硬币次数:"))
i = 0
sum1=0
sum2=0
a=0
sum3=0
sum4=0
b=0
c=0
print("开始抛硬币实验:")
while i < counts:
# 生成一个随机数num #
num=random.randrange(0, 100, 1)
if num % 2:
# 打印结果 #
if counts<100:
print("正面",end=" ")
sum1+=1
else:
if counts<100:
print("反面",end=" ")
sum2+=1
if num%2 and a%2:
sum3+=1#统计连续正面次数#
if b<=sum3:
b=sum3
else:
sum3=0
if num%2==0 and a%2==0:
sum4+=1#统计连续反面次数#
if c<=sum4:
c=sum4
else:
sum4=0
i = i + 1
a=num#记录前一次随机数值#
print("\n一共模拟了",counts,"次抛硬币,结果如下:")
print("正面:",sum1,"次")
print("反面:",sum2,"次")
print("正面最多连续出现:",b+1)
print("反面最多连续出现:",c+1) 你们发的好复杂我压根看不懂。。是我智商不够么{:10_269:}
页:
[1]