JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Java 新手區 » 語法(Syntax)  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to topicthreaded modego to previous topicgo to next topic
本主題所含的標籤
無標籤
作者 遞迴兩個回傳值
astringchun11





發文: 4
積分: 0
於 2017-09-11 16:13 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
這是java 8程式語言的利用遞迴解決費式數列的範例,我想請問第8行有兩個回傳遞迴值,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.*;
 
class Mathematics {
  long fibonacci(int n) {
    if(n <= 2) {
      return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}
 
public class Fibonacci {
 
  public static void main(String[] argv) throws IOException{
    Mathematics m = new Mathematics();
 
    BufferedReader br =
      new BufferedReader(new InputStreamReader(System.in));
 
    System.out.print("請輸入 n:");
    int n = Integer.parseInt(br.readLine());
 
    System.out.println("Fibonacci 數列第 " + n + " 項:" +
      m.fibonacci(n));
  }


當我帶入數字後,還是不懂他的邏輯順序,我的想法是這樣
n=8 fibonacci(8-1)+fibonacci(8-2)
再來傳回值會等於7還是6呢?


reply to postreply to post
作者 Re:遞迴兩個回傳值 [Re:astringchun11]
kebin_liu

雲端決策系統

版主

發文: 1861
積分: 11
於 2017-09-13 00:29 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
是各別遞迴。
用 n = 5 展開來看 (8有點多)。
f(5)
= return {f(5-1) + f(5-2)}
= return {f(4) + f(3)}
= return { {f(4-1) + f(4-2)} + {f(3-1) + f(3-2)} }
= return { {f(3) + f(2)} + {f(2) + f(1)} }
= return { { {f(3-1)+f(3-2)} + 1} + {1 + 1} }
= return { { {f(2) + f(1)} + 1} + 2}
= return { { {1 + 1} + 1} + 2}
= return { {2 + 1} + 2}
= return {3 + 2}
= return 5


reply to postreply to post
作者 Re:遞迴兩個回傳值 [Re:kebin_liu]
astringchun11





發文: 4
積分: 0
於 2017-09-13 14:42 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
感謝解答Big SmileBig SmileBig SmileBig SmileBig Smile

reply to postreply to post
» JWorld@TW »  Java 新手區 » 語法(Syntax)

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8