C++ 入門指南 4.01
練習 9.7 參考程式 - 練習設計使用者輸入的函數
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// std 為標準程式庫的命名空間
using namespace std;
// 宣告函數原型
int factorial(int);
int main(void) {
// 接收使用者輸入
int input;
cin >> input;
// 印出使用者輸入的階層值
cout << endl;
cout << factorial(input) << endl;
cout << endl;
// 最後回傳 0 給作業系統
return 0;
}
// 計算階層的遞迴函數
int factorial(int n) {
// 計算到 n 的階層
int result = 1;
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise0907.cxx
編譯:g++ exercise0907.cxx
執行:./a.out
功能:C++入門指南單元九的練習
作者:張凱慶 */
回到練習題目