C語言:python
1 /* 2 ----------------------------------- 3 當n = 1, 只有1中跳法;當n = 2時,有兩種跳法;當n = 3 時,有3種跳法;當n = 4時,有5種跳法;當n = 5時,有8種跳法 4 因此:tiaofa(n) 5 n=1時,tiaofa(1) = 1 6 n=2時,tiaofa(2) = 2 7 n>2時,tiaofa(n) = tiaofa(n-1) + tiaofa(n-2) 8 ----------------------------------- 9 */ 10 11 # include <stdio.h> 12 13 int tiaofa(int n) 14 { 15 int i, tf1, tf2, tf3; 16 tf1 = 1; 17 tf2 = 2; 18 19 if (n == 1) 20 tf3 = 1; 21 else if (n ==2) 22 tf3 = 2; 23 else 24 { 25 for (i=3; i<=n; i++) 26 { 27 tf3 = tf1 + tf2; 28 tf1 = tf2; 29 tf2 = tf3; 30 } 31 } 32 33 return tf3; 34 } 35 36 int main(void) 37 { 38 int n; 39 char ch; 40 do 41 { 42 printf("請輸入臺階數(正整數):"); 43 scanf("%d", &n); 44 printf("%d個臺階有%d種跳法。\n", n, tiaofa(n)); 45 printf("\n你想繼續嗎(Y/N):"); 46 flushall(); 47 scanf("%c", &ch); 48 } while (ch=='y' || ch=='Y'); 49 return 0; 50 } 51 52 /* 53 在Vc++6.0中的輸出結果爲: 54 ----------------------------------- 55 56 請輸入臺階數(正整數):1 57 1個臺階有1種跳法。 58 你想繼續嗎(Y/y):Y 59 請輸入臺階數(正整數):2 60 2個臺階有2種跳法。 61 你想繼續嗎(Y/y):Y 62 請輸入臺階數(正整數):3 63 3個臺階有3種跳法。 64 你想繼續嗎(Y/y):Y 65 請輸入臺階數(正整數):4 66 4個臺階有5種跳法。 67 你想繼續嗎(Y/y):Y 68 請輸入臺階數(正整數):5 69 5個臺階有8種跳法。 70 你想繼續嗎(Y/y):N 71 Press any key to continue 72 73 ----------------------------------- 74 */
Python:c++
def tf(n): if n==1: return 1 elif n==2: return 2 else: return tf(n-1)+tf(n-2) n = int(input('請輸入臺階數(正整數):')) tf_n = tf(n) print(tf_n)