我正在尝试从def方程获取整数返回

时间:2018-12-19 16:53:57

标签: python

我正在尝试获取它,因此我的代码将只返回2的整数,而不是2.5464893461251985

def number_of_cookies(amount, height, radius):
    return(amount/10)/(radius*radius*3.14158*height)

print (number_of_cookies(40, 0.5, 1))
assert number_of_cookies(40, 0.5, 1) == 2
assert number_of_cookies(400, 0.5, 1) == 25
assert number_of_cookies(1200, 0.3, 1) == 127

2 个答案:

答案 0 :(得分:0)

def number_of_cookies(amount, height, radius):
    return int((amount/10)/(radius*radius*3.14158*height))

设置为int将避免您看到的float精度

答案 1 :(得分:0)

有两种方法可以做到这一点。如果希望它成为整数,则可以使用int

def number_of_cookies(amount, height, radius):
    return int((amount / 10) / (radius * radius * 3.14158 * height))

如果要舍入到指定的小数位数,可以使用round

def number_of_cookies(amount, height, radius):
    return round((amount / 10) / (radius * radius * 3.14158 * height), 0)

最后,如果要四舍五入,可以执行以下操作:

import math
def number_of_cookies(amount, height, radius):
    return math.floor((amount / 10) / (radius * radius * 3.14158 * height))