有代碼有真相
操作計數,一個遞歸函數時,
void foo(int m)
{
++m;
foo(m);
}
調用 foo(0);
void foo(int m)
{
foo(++m);
}
調用 foo(0);
但是當存在兩個遞歸函數時
void foo(int m)
{
++m;
foo(m)
// ...
++m;
foo(m);
}
調用 foo(0);
這種方式不能正常工作,因為 m 是 int 型的,第一個 foo 改變對第二個 foo 不起作用。
應該是
void foo(int& m)
{
++m;
foo(m)
// ...
++m;
foo(m);
}
調用:
int m = 0;
void foo(m);
以下方式
void foo(int& m)
{
foo(++m);
// ...
foo(++m);
}
會造成混亂,不能正常工作。
m++, 編譯失敗,因為 m++ 的結果是 const 的。
也不能是 m + 1, 因為 m + 1 的結果也是 const 的。
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 void tower(int n, const string& a, const string& b, const string& c, int& m)
6 {
7 if (n == 1)
8 {
9 ++m;
10 cout << m << "\t";
11 cout << n << ": " << a << " -> " << b << endl;
12 return;
13 }
14 tower(n - 1, a, c, b, m);
15 ++m;
16 cout << m << "\t";
17 cout << n << ": " << a << " -> " << b << endl;
18 tower(n - 1, c, b, a, m);
19 }
20
21 int main()
22 {
23 int n;
24 while (cin >> n)
25 {
26 int m = 0;
27 tower(n, "towerA", "towerB", "towerC", m);
28 }
29 return 0;
30 }
posted on 2011-09-10 16:53
unixfy 閱讀(148)
評論(0) 編輯 收藏 引用