首页 > 解决方案 > 为什么返回 Int?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))

标签: python

解决方案


使用它来获得正确的答案:

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))

/运算符对于 python 2 和 python 3 不相似


推荐阅读