二项式系数 - 除以零误差

时间:2017-03-11 19:50:32

标签: python-3.x divide-by-zero binomial-coefficients

" main"代码用于计算每个二项式系数,除非(n = k + 1)。这是令人难以置信的 - 它说有一个零错误除法,但我不明白为什么。主函数中发生错误(d = n2 / c)。知道为什么吗?

def getInteger( prompt ):
    while True:
        try:
            num = int( input(prompt))
        except ValueError:
            print( "That is not an integer -- please try again")
            continue
        return num   

def factorial(f):
    f = f
    q = (f - 1)
    fac = (f * q)
    while (q) > 1:
        q -= 1
        fac = (fac * q)
    return (fac)


def main():
    n = getInteger("enter a factor:")
    k = getInteger("enter a factor:")
    while n >= k :
        n2 = factorial(n)
        k2 = factorial(k)
        a = n - k
        b = factorial(a)
        c = b * k2
        d = n2 / c
        print("n2 = {} k2 = {} a = {} b = {} c = {} d = {}" .format(n2, k2, a, b, c, d)  )
        return
    else:
        print("n must be larger than k")

if __name__ == '__main__':
    main()    

main()

请注意,我需要自己实现计算,因此无法使用库。

1 个答案:

答案 0 :(得分:0)

您的因子函数对于输入0,1不正确。它们都返回0,而两者都返回1。