C++编程思想 第1卷 第3章 递归

递归函数内调用自己。
递归会一直调用下去,直到内存耗尽。需要结束递归的方法。
结束的方法就是套一个if语句
在removeHat()中,只要cat值小于‘Z’,就会调用removeHat(),实现递归

每次调用removeHat,cat值增加1


//: C03:CatsInHats.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Simple demonstration of recursion
#include <iostream>
using namespace std;

void removeHat(char cat) {
  for(char c = 'A'; c < cat; c++)
    cout << "  ";
  if(cat <= 'Z') {
    cout << "cat " << cat << endl;
    removeHat(cat + 1); // Recursive call
  } else
    cout << "VOOM!!!" << endl;
}

int main() {
  removeHat('A');
  getchar();
} ///:~


输出
cat A
  cat B
    cat C
      cat D
        cat E
          cat F
            cat G
              cat H
                cat I
                  cat J
                    cat K
                      cat L
                        cat M
                          cat N
                            cat O
                              cat P
                                cat Q
                                  cat R
                                    cat S
                                      cat T
                                        cat U
                                          cat V
                                            cat W
                                              cat X
                                                cat Y
                                                  cat Z
                                                    VOOM!!!

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80575762
今日推荐