English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

假設
1,1,2,3,5,8,13,21....
這種程式要怎麼寫呢???
就寫到21就好,這是累加的!希望大家能夠幫幫我,順便附上註解
PS:不是作業只是看到書上的迴圈突然想到而以!但自己寫了一陣子又寫不太出來
所以才會想要拿到網路上問!感謝大家

2006-06-23 17:48:00 · 2 個解答 · 發問者 情關難過 1 in 電腦與網際網路 程式設計

不要用一些有的沒有含事庫唷@@"!因為我還沒學到那
就用一般的陣列和迴圈就好了!

2006-06-23 17:48:36 · update #1

另外若我要指定累加15次的話也有辨法嗎??若有的話希望你們也可以順便寫給我看看

2006-06-23 17:49:13 · update #2

2 個解答

import java.io.*;
public class Fn1
{
public static void main(String args[]) throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int i,n,x=0,newx=0,oldx=1;
System.out.print("請輸入Fn:");
n=Integer.parseInt(br.readLine());
if(n==1)
{
System.out.print("Fn="+(x+1));
}
else
{
for(i=1;i<=n-1;i=i+1)
{
x=newx+oldx;
newx=oldx;
oldx=x;
}
System.out.print("Fn="+x);
}
}
}
我想上面自已看那個會比較懂!下用的是用到遞迴!
import java.io.*;
public class Fn2
{
public static void main(String args[]) throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入Fn:");
int n=Integer.parseInt(br.readLine());
System.out.print("Fn="+fraction(n));
}
private static int fraction(int y)
{
int ans;
if (y==0)
{
ans=0;
}
else if (y<3)
{
ans=1;
}
else
{
ans=fraction(y-1)+fraction(y-2);
}
return(ans);
}
}

2006-06-26 23:59:34 · answer #1 · answered by Glove 2 · 0 0

你寫的應該是斐波那契數列,請參考 Wikipedia 上的介紹(http://zh.wikipedia.org/wiki/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B8)。以下是我寫的程式,供你參考。public class B { public static int fibonacci(int x) {  if (x == 1 || x == 2) return 1;  int a = 1; // f(n-2)  int b = 1; // f(n-1)  int c = 0; // f(n)  for (int i = 3; i <= x; i++) {   c = a + b;   a = b;   b = c;  }  return c; }  public static void main(String[] args) {  System.out.println("f(3) = " + fibonacci(3));  System.out.println("f(4) = " + fibonacci(4));  System.out.println("f(5) = " + fibonacci(5));  System.out.println("f(6) = " + fibonacci(6));  System.out.println("f(7) = " + fibonacci(7));  System.out.println("f(8) = " + fibonacci(8));  System.out.println("f(9) = " + fibonacci(9));  System.out.println("f(10) = " + fibonacci(10));  System.out.println("f(15) = " + fibonacci(15));  System.out.println("f(20) = " + fibonacci(20)); }}

2006-06-24 10:54:17 · answer #2 · answered by ? 7 · 0 0

fedest.com, questions and answers