例30:C語言求n!,要求用遞歸實現。
解題思路:本題和例29思想差不多,都是用遞歸來實現,讀者可以回顧一下《C語言 | 遞歸求年齡》
求階乘函數:
int factorial(int number)//自定義階乘函數 { int temp;//定義整型變量 if(number<0)//如果這個數小於0 { printf("錯誤數據請,輸入大於0的數!");//不符合條件,無法求 } else if(number==0||number==1)//0或者1本身的階乘是1 { temp=1; } else { temp=factorial(number-1)*number;//否則求這個數與前一個數相乘的結果 } return temp;//將temp返回到函數調用處 }
源代碼演示:
#include<stdio.h>//頭文件 int main()//主函數 { int factorial(int number);//自定義階乘函數聲明 int number,temp;//定義變量 printf("輸入要求階乘的數:");//提示語句 scanf("%d",&number);//鍵盤輸入相求的數 temp=factorial(number);//調用階乘函數 printf("%d!=%d",number,temp) ;//輸出結果 return 0;//主函數返回值為0 } int factorial(int number)//自定義階乘函數 { int temp;//定義整型變量 if(number<0)//如果這個數小於0 { printf("錯誤數據請,輸入大於0的數!");//不符合條件,無法求 } else if(number==0||number==1)//0或者1本身的階乘是1 { temp=1; } else { temp=factorial(number-1)*number;//否則求這個數與前一個數相乘的結果 } return temp;//將temp返回到函數調用處 }
編譯運行結果如下:
輸入要求階乘的數:5 5!=120 -------------------------------- Process exited after 1.553 seconds with return value 0 請按任意鍵繼續. . .
上述代碼我定義的是int類型,因為這個數不可能無限大,如果特別大,會超過int的范圍,如下:
輸入要求階乘的數:100 100!=0 -------------------------------- Process exited after 1.575 seconds with return value 0 請按任意鍵繼續. . .
留個問題給讀者請思考,最大可以求幾的階乘,為什么?