【发布时间】:2020-10-27 21:28:50
【问题描述】:
问题是
编写一个程序,将两个随机生成的介于 1 和 100 之间的自然数(正整数)的和 (a+b) 和乘积 (a*b) 打印给用户。要赢得游戏,用户必须猜出这两个数字,猜测的顺序应该无关紧要。给用户三个猜测,如果在三个猜测之后他们是错误的,那么数字就会显示给他们。用户必须在单轮中正确猜测两个猜测,并且不会被告知前一轮中的一个数字是否正确。 用户有 3 次尝试猜这两个数字,如果用户猜对了数字,则游戏应该结束。
import random
a = random.randint(1,100)
b = random.randint(1,100)
print("Sum of two random number is",a + b)
print("Product of two random number is", a * b)
print("Try to guess the 2 numbers that make this sum and product, you have 3 tries, good luck!")
count = 0
win = 0
while count != 3:
guess_a = int(input('Guess first number '))
guess_b = int(input('Guess second number '))
if count == 3:
break
if ((guess_a == a) or (guess_b == b)) and ((guess_b == a) or (guess_a == b)):
win = 1
break
else:
count = count + 1
print('Incorrect!!!')
if win == 1:
print('Congrats you won the game.')
else:
print('You lost the game.')
print('Number a was:',a)
print('Number b was',b)
我试过这个它有点工作,但我不知道如何使猜测数字的顺序无关紧要。
【问题讨论】:
-
试试:
((guess_a == a) and (guess_b == b)) or ((guess_b == a) and (guess_a == b)) -
使用
set:{guess_a, guess_b} == {a, b} -
@hiroprotagonist 如果 a 和 b 恰好相同怎么办?
-
设置的解决方案非常整洁。如果 a 和 b 相同,它仍然可以工作,请尝试一下,然后您需要输入相同的数字才能正确。顺便说一句,任何具有基本数学技能的人都不需要“猜测”答案;-)
-
@rajah9
{3, 3} == {3, 3}是True。或者你认为什么行不通?
标签: python