標籤:return == code nbsp scanf tin turn div clu
C語言:
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 else24 {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 do41 {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 請輸入台階數(正整數):157 1個台階有1種跳法。58 你想繼續嗎(Y/y):Y59 請輸入台階數(正整數):260 2個台階有2種跳法。61 你想繼續嗎(Y/y):Y62 請輸入台階數(正整數):363 3個台階有3種跳法。64 你想繼續嗎(Y/y):Y65 請輸入台階數(正整數):466 4個台階有5種跳法。67 你想繼續嗎(Y/y):Y68 請輸入台階數(正整數):569 5個台階有8種跳法。70 你想繼續嗎(Y/y):N71 Press any key to continue72 73 -----------------------------------74 */
Python:
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)
青蛙跳台階(C、Python)