将int加在一起并得到错误的ans

2024-09-30 05:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个赌场骰子游戏,要求用户输入赌注和骰子号码。骰子数的结果将从余额中扣除赌注或将赌注*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

Tags: numberyourisdicenow余额intprint
2条回答

这真的很有趣。在这里输入一个字符串:

Wager = input("Please enter a wager: ")

在您的例子中,Wager字符串"5"。然后,将这个字符串乘以6:

Winnings = int(Wager * 6)

这与Winnings = int("5"* 6)相同,但是"5"* 6 == '555555'!然后,int将其转换为整数,得到的结果不正确

您想将什么转换为整数:字符串"5"* 6还是字符串"5"?你的意思肯定是:

Winnings = int(Wager) * 6

在相乘之前,您需要转换下注字符串

Winnings = int(Wager) * 6

Wager是一个字符串,因此'5'和相乘字符串是允许的,这将生成一个新字符串,其值重复:

>>> '5' * 6
'555555'

然后,转换新字符串,将产生比预期更大的胜利

最好尽早转换用户输入,这样在代码的其他地方就更难犯这样的错误。这也有助于减少将输入转换为整数所需的位数:

Wager = int(input("Please enter a wager: "))
UserNumber = int(input("Enter a number: "))

相关问题 更多 >

    热门问题