一個正整數n,寫爲n的階乘!定義爲:任何人都可以幫助找出這個遞歸2.7 python代碼?
N *(N-1)第(n-2)... * 1 如果n是0 N!定義爲1 如果n是負數,n!未定義
一個例子是: 12! = 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
編寫程序 1.從用戶輸入正整數。如果整數不爲正,則顯示錯誤消息 2.提示用戶要麼已經階乘通過順序編程(選項1),或者由遞歸(選項2)
選項1計算:使用中的所述一個 自頂向下迭代方法(例如while,for)找到任何正整數(包括0)的階乘。使用遞歸(見文第6.3節),找到任何正整數的階乘(包括0)
- 打印階乘
:
選項2向此作業提交一份Word文檔(版本2010或更早版本),其中包含程序的源代碼和使用這兩種選項運行的屏幕截圖,並且對於每個選項,使用0,9和-4。你會需要的d來定義一個函數來執行這個任務,使用遞歸 不要嘗試這個數字太大---這可能會產生一個錯誤,因爲它需要執行的內存
我似乎已經想出瞭如何做功能;然而,我似乎無法讓他們在main()函數中工作。
當我運行我的程序時,Menu()函數執行;然而,當我輸入1或2,我的程序返回
(Traceback (most recent call last): File "C:/Users/user/Documents/Prjct4", line 59, in <module> main() File "C:/Users/user/Documents/Prjct4", line 54, in main num = factorial() UnboundLocalError: local variable 'factorial' referenced before assignment)
以下是我迄今爲止:
def Menu():
print
print ("For Sequential Programming Calculator, Enter 1")
print ("For Recursion Calculator, Enter 2")
print
while True:
choice = input("Enter your choice here: ")
if (choice >= 1) and (choice <=2) and (int(choice)==choice):
return choice
else:
print ("Invalid Choice! Please enter 1 or 2")
def factorial():
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print "The factorial of",num,"is",factorial(num)
def recur_factorial():
if n == 1:
return n
else:
factorial= n*recur_factorial(n-1)
return factorial
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print "The factorial of 0 is 1"
else:
print "The factorial of",num,"is",recur_factorial(num)
def main():
print
print("Factorial Calculator")
print
while True:
choice = Menu()
if choice == 1:
num = factorial()
elif choice == 2:
factorial = recur_factorial()
main()
如果有人可以幫助我弄清楚了這一點,我將不勝感激它!謝謝!
你到底在問什麼? 「似乎無法讓他們工作」是什麼意思? – GreenAsJade
當我運行我的程序時,Menu()函數執行;但是,在輸入1或2後,我的程序返回(Traceback(最近呼叫最後一個): 文件「C:/ Users/user/Documents/Prjct4」,第59行, main() 文件「 /用戶/用戶/文檔/ Prjct4「,第54行,主 num = factorial() UnboundLocalError:賦值之前引用的局部變量'factorial' –
BHR77
@ BHR77在factorial = recur_factorial行中更改變量名'factorial' ()'不匹配函數的名字 – halex