为什么返回Int?python

2024-06-09 00:57:40 发布

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

在这段视频中(7分30秒),我从这段视频中复制的下面的代码返回3,虽然 地雷返回4.04秒。 我不明白为什么视频中的代码返回Int,尽管我的代码返回Float

https://www.youtube.com/watch?v=HWW-jA6YjHk&list=UUNc-Wa_ZNBAGzFkYbAHw9eg&index=29

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += cents / coin
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))

Tags: of代码https视频returnifyoutubewww
1条回答
网友
1楼 · 发布于 2024-06-09 00:57:40

使用此选项可获得正确答案:

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += int(cents / coin)
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))

/运算符对于Python2和Python3不相似

相关问题 更多 >