2

我尝试制作一个执行斐波那契数列的 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 语句。有人会好心让我的代码工作吗?或者也许可以制作一种更短的代码。我是初学者,所以要冷静。谢谢 :)

4

15 回答 15

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);        
        }            
    }
}    

这是使用缓冲阅读器完成的......如果据说你只使用缓冲阅读器,那么你可以使用 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...
        }            
    }
}    

所以在这里我给了你三种方法,它们应该给出相同的输出(很可能)选择对你方便的那个..

于 2020-05-24T07:36:40.937 回答
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

于 2013-08-18T06:35:35.977 回答
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

于 2013-08-18T06:39:04.943 回答
0

更简单的方法

public static void main(String[] args) {

    int first = 1;
    int second = 2;
    for (int i = 0; i < 20; i++) {
        if (i == 0)
            System.out.print(first);
        System.out.print("," + second);
        int temp = second;
        second = first + second;
        first = temp;
    }
}```

程序输出:1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946

于 2021-09-09T07:18:01.380 回答
0

这是我在网上找到的另一种算法,我从中简化了代码。

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,所以我给你这个链接,只是想对你有所帮助。

于 2019-12-27T20:56:21.083 回答
0

我也是java的初学者,但是我找到了一种使用数组创建斐波那契数的简单方法。斐波那契数的基本原理是当前数与前数相加。 这是我的代码:

//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];
}
于 2016-12-01T21:45:04.597 回答
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

于 2020-08-27T18:31:21.710 回答
-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;
    }
于 2014-05-08T07:30:34.190 回答
-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
*/

}

于 2015-04-27T22:04:12.040 回答
-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] + " ");
         }
    }
}
于 2014-08-30T09:52:15.193 回答
-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;
        }
    }
}
于 2013-11-29T02:08:57.580 回答
-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;

 }
于 2015-05-15T19:36:25.420 回答
-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();
    }
}
于 2015-06-29T19:04:11.683 回答
-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;
        }
    }
}
于 2016-08-03T19:58:03.780 回答
-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;
        }
    }
}
于 2017-07-29T23:39:53.393 回答