用python计算1*-2*3*-4*...n
时间: 2023-07-23 16:43:07 浏览: 53
可以使用类似上面的方法,只不过在计算时需要判断当前的数是奇数还是偶数,来决定是否取反。具体实现代码如下:
```python
def product(n):
if n == 1:
return 1
else:
if n % 2 == 0:
return -n * product(n-1)
else:
return n * product(n-1)
n = 6
print(product(n)) # 输出 -720
```
在这个代码中,函数 `product(n)` 也会不停地调用自身,并将 `n` 不断减一直到 1。当 `n` 等于 1 时,函数返回 1。在每次递归调用时,我们会判断当前的数是奇数还是偶数,如果是偶数,我们就将其取反,即乘上 -1。最后,所有递归调用返回的结果会相乘得到最终的答案。在这个例子中,我们传入了 6,结果为 1*-2*3*-4*5*-6=-720。
相关问题
用python计算1*(-2)*3*(-4)*...n
同样可以使用递归函数来计算这个式子,只需要在每次递归调用时判断当前的数是奇数还是偶数,来决定是否乘上 -1。具体实现代码如下:
```python
def product(n):
if n == 1:
return 1
else:
if n % 2 == 0:
return (-1)*n * product(n-1)
else:
return n * product(n-1)
n = 6
print(product(n)) # 输出 -720
```
在这个代码中,函数 `product(n)` 也会不停地调用自身,并将 `n` 不断减一直到 1。当 `n` 等于 1 时,函数返回 1。在每次递归调用时,我们会判断当前的数是奇数还是偶数,如果是偶数,我们就将其乘上 -1。最后,所有递归调用返回的结果会相乘得到最终的答案。在这个例子中,我们传入了 6,结果为 1*(-2)*3*(-4)*5*(-6)=-720。
python用函数计算1*2*3*4*...n
可以使用递归函数来计算1*2*3*4*...n,代码如下:
```python
def product(n):
if n == 1:
return 1
else:
return n * product(n-1)
n = 5
print(product(n)) # 输出 120
```
在这个代码中,函数 `product(n)` 会不停地调用自身,并将 `n` 不断减一直到 1。当 `n` 等于 1 时,函数返回 1。最后,所有递归调用返回的结果会乘起来得到最终的答案。在这个例子中,我们传入了 5,结果为 1*2*3*4*5=120。