我正在努力学习递归,并编写了这段代码来返回从一个到所选数字的所有数字的总和。当我运行程序时,无论我最初输入什么数字,它给我的总和总是“无”,我的意思是,我的程序中outputSum变量的值似乎是“无”。我认为改变SUM_OF_NUMBERS的初始化值可能会改变这一点,但事实并非如此,我仍然将“无”作为输出。任何人都可以指向我的代码中导致此错误的部分吗?
def sumOfNumbers(number):
SUM_OF_NUMBERS = 0
if number > 0:
SUM_OF_NUMBERS = SUM_OF_NUMBERS + number
else:
return SUM_OF_NUMBERS
number = number - 1
sumOfNumbers(number)
def main():
repeat = 'Y'
outputSum = 0
while repeat == 'Y' or repeat == 'y':
print("Welcome to the Sum Of Numbers program!")
number = int(input("\nPlease enter a number to sum up: "))
outputSum = sumOfNumbers(number)
print("\nThe sum of all numbers from 1 to " + str(number) + \
" is " + str(outputSum))
repeat = input("\nWould you like to sum up another number?" \
'\nEnter "Y" for "YES" or "N" for "NO": ')
if repeat == 'N' or repeat == 'n':
print("\nThank you for using the program.")
else:
print("\nSorry, that was not a valid option.")
repeat = input('Please enter "Y" for "YES" or "N" for "NO": ')
main()
答案 0 :(得分:2)
您收到None
,因为当输入大于0
时您没有返回任何内容。
比你拥有的要简单得多。
def sumOfNumbers(number):
if number > 0:
return number + sumOfNumbers(number-1)
else:
return 0
答案 1 :(得分:1)
def sumOfNumbers(n):
if n>0:
return n+sumOfNumbers(n-1)
else:
return 0
i = input("Enter a number")
print "Sum of numbers:",sumOfNumbers(i)
答案 2 :(得分:0)
或者,只需预先测试边界条件,并处理(尾部)递归,
def sumOfNumbers(number):
if number <= 0: return 0
return number+sumOfNumbers(number-1)
答案 3 :(得分:0)
你的逻辑是合理的。问题是您每次都将SUM_OF_NUMBERS重置为0。此外,它返回None,因为您忘记了最终的return语句。要解决此问题,您可以将其作为参数传递,如:
def sumOfNumbers(number, SUM_OF_NUMBERS = 0):
if number > 0:
SUM_OF_NUMBERS = SUM_OF_NUMBERS + number
else:
return SUM_OF_NUMBERS
number = number - 1
return sumOfNumbers(number, SUM_OF_NUMBERS)
答案 4 :(得分:0)
有两件小事:
这里简化一下简短的代码:
def recursive_sum(num):
if num == 0:
return 0
return num + recursive_sum(num-1)