我正在写一个赌场骰子游戏,要求用户输入赌注和骰子号码。骰子数的结果将从余额中扣除赌注或将赌注*6添加到余额中。当用户猜测错误时,将从余额中扣除正确的值
剩余余额为490,下注5后下注获胜,新余额为556045。这显然应该是520
为什么新的余额是556045
下面是我的代码和输出
import random
print("Welcome to the casino")
UserName = input("Please enter your name: ")
print("Thanks for playing " + UserName + "! We wish you the best of luck!")
balanceRemaining = 500
while balanceRemaining != 0:
RandomNumber = random.randint(1, 6)
Wager = input("Please enter a wager: ")
UserNumber = input("Enter a number: ")
print("Dice number was " + str(RandomNumber))
if int(UserNumber) != RandomNumber:
balanceRemaining = balanceRemaining - int(Wager)
print("Your Balance is now: " + str(balanceRemaining))
else:
Winnings = int(Wager * 6)
balanceRemaining = int(Winnings) + int(balanceRemaining)
print("Your Balance is now: " + str(balanceRemaining))
输出
Please enter a wager: 5
Enter a number: 5
Dice number was 1
Your Balance is now: 495
Please enter a wager: 5
Enter a number: 5
Dice number was 6
Your Balance is now: 490
Please enter a wager: 5
Enter a number: 5
Dice number was 5
Your Balance is now: 556045
这真的很有趣。在这里输入一个字符串:
在您的例子中,
Wager
是字符串"5"
。然后,将这个字符串乘以6:这与
Winnings = int("5"* 6)
相同,但是"5"* 6 == '555555'
!然后,int
将其转换为整数,得到的结果不正确您想将什么转换为整数:字符串
"5"* 6
还是字符串"5"
?你的意思肯定是:在相乘之前,您需要转换下注字符串:
Wager
是一个字符串,因此'5'
和相乘字符串是允许的,这将生成一个新字符串,其值重复:然后,转换新字符串,将产生比预期更大的胜利
最好尽早转换用户输入,这样在代码的其他地方就更难犯这样的错误。这也有助于减少将输入转换为整数所需的位数:
相关问题 更多 >
编程相关推荐