Java中的Fibonacci序列用于语句

时间:2013-08-18 06:30:20

标签: java for-loop fibonacci

我尝试制作一个执行Fibonacci序列的Java程序。

这是我的代码:

import java.io.*;
public class Fibonacci{
    public static void main(String[]args){
        BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
        int ctr1=0;
        int ctr2=0;
        int num1=0;
        int num2=0;
        int num3=0;
        try{
            System.out.println("How many numbers would you want to see?");
            ctr2=Integer.parseInt(Data.readLine());
            for(int ans=0; ctr1==ctr2; ctr1++){
            num1++;
            System.out.println(num2 + "\n" + num1);
            ans=num1+num2;
            System.out.println(ans);
            ans=num3;
            }
        }catch(IOException err){
            System.out.println("Error!" + err);
        }catch(NumberFormatException err){
            System.out.println("Invald Input!");
        }
    }
}

显然,我是Java的初学者,我不知道如何正确使用for语句。有人会善待我的代码吗?或者可以使代码更短的代码。我是初学者,所以要冷静。谢谢:))

14 个答案:

答案 0 :(得分:1)

Java中的斐波那契数列实际上非常简单,只需一个for循环即可完成!!!

import java.io.*;
class fibonacci{    
    public static void main() throws NumberFormatException, IOException{  
        BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
        int a,b,c,d;
        System.out.println("Upto How many numbers do you want to see?");
        d=Integer.parseInt(Data.readLine());
        for  (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){            
            System.out.println(a);        
        }            
    }
}    

这是使用缓冲读取器完成的.....如果据说只使用bufferedreader,则可以使用Scanner类,该类非常简单易用,因为您不必捕获或引发任何异常.....

扫描程序:-

import java.util.*;
class fibonacci{    
    public static void main(){  
        Scanner sc = new Scanner(System.in);
        int a,b,c;
        System.out.println("Upto How many numbers do you want to see?");
        d=sc.nextInt();
        for  (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){            
            System.out.println(a);        
        }            
    }
}    

现在,正如我在一个循环中所说的,您可以执行此操作。...这是另一种方法,您可以在循环体内进行交换,而不是在循环的参数中进行交换... 对于初学者来说,这很容易理解,因为您不必在参数内传递多个变量,是的,它会更长一些

import java.util.*;
class fibonacci{    
    public static void main(){  
        Scanner sc = new Scanner(System.in);
        int a = 0,b = 1,c,d;
        System.out.println("Upto How many numbers do you want to see?");
        d=sc.nextInt();
        System.out.println(a +"\n" +b);//\n is used to go to next line....
        for  (c=0;c<d;c++){  
            c = a + b;//Doing and printing the fibonacci...
            System.out.println(c);     
            a = b;
            b = c;//Swapping the values...
        }            
    }
}    

所以在这里,我给了您三种方法,它们应该给出相同的输出(最有可能),选择对您方便的一种。

答案 1 :(得分:0)

请查看此代码段,这比您理解的要容易得多。解决方案提示很简单,你为前2个斐波那契数字保留2个指针并在循环中适当地更新它们。在下面的示例中,循环执行10次,您可以根据需要进行修改。

static void fibonacci() {
    int ptr1 = 1, ptr2 = 1;
    int temp = 0;
    System.out.print(ptr1 + " " + ptr2 + " ");
    for (int i = 0; i < 10; i++) {
        System.out.print(ptr1 + ptr2 + " ");
        temp = ptr1;
        ptr1 = ptr2;
        ptr2 = temp + ptr2;
    }
}

<强>输出:

  

1 1 2 3 5 8 13 21 34 55 89 144

答案 2 :(得分:0)

扩展答案,如果你想看起来很酷,请使用递归。

public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = 300; // how many numbers you want to generate
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }
}

以下是谷歌搜索它的内容,希望这些资源有所帮助:http://bit.ly/1cWxhUS

答案 3 :(得分:0)

我是java的初学者,但是我找到了一种使用数组创建斐波纳契数的简单方法。 Fibonacci数的基本原理是添加当前数字和之前的数字。   这是我的代码:

//Creation of array 
int [ ] fib = new int[size];

//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;

//Creating variable "a" to use in for loop
int a = 1

//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{   
  fib[i] = a;
  a = fib[i] + fib[i-1];
}

答案 4 :(得分:0)

这是我发现的online的另一种算法,并从中简化了代码。

public static BigInteger fib(BigInteger x) {
        if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
        int n = Integer.valueOf(x.toString());
        BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
        for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
            BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
            BigInteger e = a.multiply(a).add(b.multiply(b));
            a = d;
            b = e;
            if ((n & bit) != 0) {
                BigInteger c = a.add(b);
                a = b;
                b = c;
            }
        }
        return a;
    }

我知道您有可能不了解如何使用BigInteger,所以我给您这个link,只是想提供帮助。

答案 5 :(得分:0)

Here we get Fibonacci Series up to n.

public static void fibSequence(int n) {
        int sum = 0;
        for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
            System.out.print(sum + " ");
        }
    }

示例:

输入: n = 20

输出: 0 1 1 2 3 5 8 13

答案 6 :(得分:-1)

import java.util.*;

public class sequence1 
{
    public static void main(String[] args) 
    {
        sequence1 fs=new sequence1();
        fs.fibonacci(); 
    }
    public void fibonacci() 
    {
        int numb1 = 1;
        int numb2 = 1;
        int temp = 0;

        @SuppressWarnings("resource")
        Scanner input=new Scanner(System.in);
        System.out.println("How Many Terms? (Up To 45)");
        int x=input.nextInt();
        x=x-2;

        System.out.println(numb1);
        System.out.println(numb2);

        for (int i = 0; i < x; i++) 
        {
            System.out.println(numb1 + numb2 + " ");
            temp = numb1;
            numb1 = numb2;
            numb2 = temp + numb2;
        }
    }
}

答案 7 :(得分:-1)

此函数返回斐波纳契数列

/**
     * @param startElement   
     * @param secondElent
     * @param length  :length of fibonacci series
     * @return fibonacciseries : contain the series of fibonacci series
     */
    public int[] createFibonacciSeries(int startElement, int secondElent,
            int length) {
        int fibonacciSeries[] = new int[length];
        fibonacciSeries[0] = startElement;
        fibonacciSeries[1] = secondElent;
        for (int i = 2; i < length; i++) {
            fibonacciSeries[i] = fibonacciSeries[i - 1]
                    + fibonacciSeries[i - 2];
        }

        return fibonacciSeries;
    }

答案 8 :(得分:-1)

import java.util.*;

class MyFibonacci {

    public static void main(String a[]){

         int febCount = 15;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i=2; i < febCount; i++){
             feb[i] = feb[i-1] + feb[i-2];
         }

         for(int i=0; i< febCount; i++){
                 System.out.print(feb[i] + " ");
         }
    }
}

答案 9 :(得分:-1)

public class FibonacciExercitiu {

public static void main(String[] args) {


    int result = fib(6); //here we test the code. Scanner can be implemented.
    System.out.println(result);

}

public static int fib(int n) {

    int x = 1;
    int y = 1;
    int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.

    for (int i = 0; i < n - 2; i++) {
        z = x + y;
        x = y;
        y = z;

    }

    return z;
}

/*
1.   F(0) = 1 (x)
2.   F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3                            // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/

}

答案 10 :(得分:-1)

 public static int[] fibonachiSeq(int n)
 {
     if (n < 0)
         return null;

    int[] F = new int[n+1];

    F[0] = 0;
    if (n == 0)
        return F;
    F[1] = 1;

    for (int i = 2; i <= n; i++)
    {
        F[i] = F[i-1] + F[i-2];
    }



    return F;

 }

答案 11 :(得分:-1)

使用while循环

class Feb
{
    static void Main(string[] args)
    {
        int fn = 0;
        int sn = 1;
        int tn = 1;

        Console.WriteLine(fn);
        Console.WriteLine(sn);
        while (true)
        {
            tn = fn + sn;

            if (tn >10)
            {
                break;
            }
            Console.WriteLine(tn);
            fn = sn;
            sn = tn;
        }
        Console.Read();
    }
}

答案 12 :(得分:-1)

公共课Febonacci {

public static void main(String[] args) {
    int first =0;
    int secend =1; 
    System.out.print(first+","+secend);
    for (int k=1;k<7;k++){
        System.out.print(","+(first+secend ));
        if(k%2!=0)
            first+=secend;
        else 
            secend+=first;
        }
    }
}

答案 13 :(得分:-1)

public class FibonacciSeries {

    public static void main(String[] args) {
        int a=0, c=0, b=1;
        for(int i=0; i<10; i++) {
            System.out.print(c+" ");
            a = c + b;
            c = b;
            b = a;
        }
    }
}