C++ 入門指南 4.01
練習 10.7 參考程式 - 練習設計階層數類別
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// std 為標準程式庫的命名空間
using namespace std;
// 宣告 FactorialDemo 類別
class FactorialDemo {
// 宣告 public 成員
public:
int value;
void Compute(int);
};
// 實作 FactorialDemo 的 Compute() 成員函數
void FactorialDemo::Compute(int p) {
// 計算到 n 的階層
int result = 1;
for (int i = 1; i <= p; i++) {
result *= i;
}
value = result;
}
int main(void) {
// 宣告建立 FactorialDemo 物件
FactorialDemo a;
// 接收使用者輸入
int input;
cin >> input;
// 印出使用者指定的階層數
cout << endl;
a.Compute(input);
cout << a.value << endl;
cout << endl;
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise1007.cxx
編譯:g++ exercise1007.cxx
執行:./a.out
功能:C++入門指南單元十的練習
作者:張凱慶 */
回到練習題目