中央論壇 - CENTER BBS

標題: 加計數器 [打印本頁]

作者: f66666602    時間: 2007-8-14 04:41
標題: 加計數器
  1. #include <iostream>
  2. using namespace std;

  3. int HanoiTower(int ,char,char,char);  //return 型態改為int

  4. void main()
  5. {

  6.         int n;
  7.         char A = 'A' , B = 'B' , C = 'C', ans;

  8.         do
  9.         {
  10.                 cout << "Hanoi Tower Implementaion\n";
  11.                 cout << "How many disks in A ? ";
  12.                 cin >> n;
  13.                
  14.                 if ( n == 0 )
  15.                         cout << "no disk to move.\n";
  16.                 else
  17.                      cout<< "共輸出" << HanoiTower(n,A,B,C)<< "次" << endl;   //HanoiTower函數會return int
  18.    
  19.                 cout << "Do you want to continue?\n";
  20.                 cin >> ans;
  21.         }while(ans=='Y' || ans=='y');

  22. }

  23. int HanoiTower(int n,char a,char b,char c)  //傳回型態改為int
  24. {
  25.         static int i=0;  // 設一個靜態int變數,不設的話 會return都會是1而以
  26.             if ( n == 1 )
  27.                 {cout << "Move disk from " << a << " -> " << c << endl;  i++;}//cout一次 ,i 就加一次
  28.         else
  29.         {
  30.                 /*將A上n-1個盤子借助C移至B */
  31.                 HanoiTower(n-1,a,c,b);
  32.                 cout << "Move disk from " << a << " -> " << c << endl;
  33.                                 i++;  //cout一次 ,i 就加一次
  34.                 /*將B上n-1個盤子借助A移至C */
  35.                 HanoiTower(n-1,b,a,c);
  36.         }
  37.                 return i;   //把最後輸出次數 return給main
複製代碼





歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3