[Knife Test 1] qingta, niudao test Tower
[Knife Test 1] qingta
Knowledge:
1. Recursion
2. Functions
3. If-else
4. Static variables
// Linglong Tower
The tower is A game with three towers marked as A, B, and C respectively. There are n plates on A tower,
The game is arranged from bottom up from big to small. The purpose of the game is to move the plate of tower A to Tower C,
After each move, big dishes are not allowed to appear on small dishes.
Analysis:
To move the plate of tower A to Tower C, we must use Tower B (except when n = 1) and move it again.
To Tower C.
When n = 1, A-> C
When n = 2, A-> B, A-> C, B-> C
When n = 3, A-> C, A-> B, C-> B, A-> C, B-> A, B-> C, A-> C
When n = ....
Answer: Use recursive functions (self-called)
# Include <stdio. h> // tower function definition. Recursive (self-called) // The parameters are: number of layers, tower A, tower B, and tower Cvoid tower (int num, char a, char B, char c) {staticint count = 0; // static local variable. The lifecycle is the whole program if (num = 1) {count ++; // count = count + 1; printf ("Step % 3d: % c-> % c \ n", count, a, c); // % 3d is 3} else {count ++; tower (num-1, a, c, B); // call your own printf ("Step % 3d: % c-> % c \ n", count,, c); tower (num-1, B, a, c);} return;} int main (void) {intn; // n is the number of layers in tower A printf ("input A number of layers:"); scanf ("% d", & n); // call tower of function tower (n, 'A', 'B', 'C'); return0 ;}
Running result:
[Smile at your fingertips] errors are inevitable. I hope you can get your corrections ^-^
Reprinted when retaining the original link http://codingit.howbbs.com and http://blog.csdn.net/mirrorsbeyourself