from random import random def printIntro(): print("学号09,题目为模拟羽毛球") def getInputs(): a = eval(input("请输入选手A的能力值(0—1):")) b = eval(input("请输入选手B的能力值(0—1):")) return a, b def simNgames(n, probA, probB): winsA, winsB = 0, 0 for i in range(n): scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: scoreA += 1 else: serving = "B" else: if random() < probB: scoreB += 1 else: serving = "A" return scoreA, scoreB def gameOver(a, b): if (a >= 20 or b >= 20): if (abs(a - b) == 2 and a <= 29 and b <= 29): return True else: return a == 30 or b == 30 else: return False def main(): printIntro() probA, probB = getInputs() winsA, winsB = simNgames(3, probA, probB) print("选手A获胜{}场比赛,赢比赛的概率为{:0.1%}".format(winsA, winsA / 3)) print("选手B获胜{}场比赛,赢比赛的概率为{:0.1%}".format(winsB, winsB / 3)) main()