如何根据乘法函数进行阶乘?多数民众赞成我所拥有的和我遇到的问题是它给了我0而不是5!= 120。
编辑NEWEEST:如何修复双因素来给我正确的数字? 如果我做5,那它应该给我5 !! = 15但是它给了我12为什么呢?
消息来源
def multiply(num1,num2):
sum_of_multiplication= 0
for i in range(num2):
sum_of_multiplication = add(sum_of_multiplication,num1)
return sum_of_multiplication
def factorial(num1):
factorial_num = num1
for i in range(1,num1):
num1 = multiply(factorial_num,num1)
print(factorial_num)
print(str(num1) + "!= " + str(factorial_num))
def double_factorial(num1):
double_factorial_num = 2
for i in range(1,num1-2):
double_factorial_num = multiply(double_factorial_num, i)
print(double_factorial_num)
print(str(num1) + "!!= " + str(double_factorial_num))
double_factorial = double_factorial(int(input("please enter your intger:")))
答案 0 :(得分:0)
这是因为你在乘法中包含0。在范围函数中(在阶乘函数中),将1
作为第一个参数使其看起来像range(1,num1)
。这样,乘法将从1
开始,而不是0
。
答案 1 :(得分:0)
由于factorial()
问题导致range()
略有偏差,这是一个很容易犯的错误,但您应该可以通过查看range()
的文档来快速解决问题。但是,您的double_factorial()
函数没有成功的希望,因为您未能预先处理关键问题,数字的奇偶校验(奇数或偶数):
def add(a, b):
return a + b
def multiply(a, b):
my_sum = 0
for _ in range(b):
my_sum = add(my_sum, a)
return my_sum
def factorial(number):
product = 1
for multiplicand in range(2, number + 1):
product = multiply(product, multiplicand)
print(str(number) + "!", "=", product)
def double_factorial(number):
parity = number % 2 + 2 # start at 2 or 3
product = 1
for multiplicand in range(parity, number + 1, 2):
product = multiply(product, multiplicand)
print(str(number) + "!!", "=", product)
number = int(input("please enter your integer: "))
factorial(number)
double_factorial(number)
<强>输出强>
> python3 test.py
please enter your integer: 5
5! = 120
5!! = 15
>