我正在写一个赌场骰子游戏,要求用户输入一个赌注和一个骰子号码。骰子数的结果将从余额中减去下注或将余额* 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
答案 0 :(得分:2)
您需要先将投注字符串转换为 ,然后再乘以
:Winnings = int(Wager) * 6
Wager
是一个字符串,因此'5'
是允许的,并且允许将字符串相乘,从而产生一个具有重复值的新字符串:
>>> '5' * 6
'555555'
然后转换该新字符串,将产生比您预期更大的获胜机会。
最好先转换用户输入 ,这样很难在代码中的其他地方犯这样的错误。这也有助于减少将输入转换为整数所需的位数:
Wager = int(input("Please enter a wager: "))
UserNumber = int(input("Enter a number: "))
答案 1 :(得分:0)
这实际上很有趣。在这里输入一个字符串:
Wager = input("Please enter a wager: ")
在您的情况下,Wager
是 string "5"
。然后,将这个 string 乘以6:
Winnings = int(Wager * 6)
与Winnings = int("5"* 6)
相同,但是"5"* 6 == '555555'
!然后,int
将其转换为整数,您将得到不正确的结果。
您想将什么转换为整数:字符串"5"* 6
或字符串"5"
?您最肯定的意思是:
Winnings = int(Wager) * 6