猿问

斐波那契数列 java

我已经生成了一个程序来计算斐波那契数列,其限制由用户通过键盘给出,但是我遇到了一个问题,因为我已经要求该数列从 1 开始,而不是像我所做的那样从 0 开始。我怎样才能做到这一点?我的斐波那契数列显示我从 1 而不是从 0?


     int maxNumber = 0; 

     int previousNumber = 0;

     int nextNumber = 1;


        System.out.println("How many numbers you want in Fibonacci:");

        Scanner scanner = new Scanner(System.in);

        maxNumber = scanner.nextInt();

        System.out.print("Fibonacci Series of "+maxNumber+" numbers:");


        for (int i = 1; i <= maxNumber; ++i)

        {

            System.out.print(previousNumber+" ");



            int sum = previousNumber + nextNumber;

            previousNumber = nextNumber;

            nextNumber = sum;

        }


慕尼黑5688855
浏览 115回答 3
3回答

BIG阳

只需做一个简单的更改并在计算后打印数字。for (int i = 1; i <= maxNumber; ++i)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// System.out.print(previousNumber+" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int sum = previousNumber + nextNumber;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; previousNumber = nextNumber;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nextNumber = sum;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(previousNumber+" ");&nbsp; &nbsp; &nbsp; &nbsp; }

猛跑小猪

使用int previousNumber = 1;,它将从 1 开始。

哈士奇WWW

/*Java Program to find the FibonacciSeries */public class FibonacciSeries {&nbsp; &nbsp;public static void main(String a[]){&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int limit = 15; /* give limit here */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int[] feb = new int[limit];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;feb[0] = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;feb[1] = 1;&nbsp; &nbsp;/* store all elements in array feb[] */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(int i=2; i < limit; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;feb[i] = feb[i-1] + feb[i-2];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; /* print all array elements */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(int i=0; i< limit; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print(feb[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答