posts - 183,  comments - 10,  trackbacks - 0
有代码有真相
操作计数,一个递归函数时,
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 阅读(138) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理