Fibonacci序列在java中使用do-while循环?

时间:2013-10-11 05:22:37

标签: java while-loop sequence fibonacci

我正在尝试使用java中的do-while循环打印 Fibonacci 序列,并且无法理解这一点。需要在0到100之间。

我有以下代码:

int prevPrevVal = 0;
int prevVal = 1;
int currVal;
System.out.println(prevPrevVal);
System.out.println(prevVal);

do
{       
    currVal = prevVal + prevPrevVal;
    System.out.println(currVal);

    prevPrevVal = prevVal;
    prevVal = currVal;          
} while (prevVal <= 100);

6 个答案:

答案 0 :(得分:2)

这是一个简化的程序,它通过在while循环中提供条件限制来找出斐波那契数列。希望你们对此有所了解...!

    int a=0;
    int b=0;
    int temp=1;
    do {    
        a=b;
        b=temp;
        temp=a+b;
        System.out.println(temp);
    }while(temp<100);

答案 1 :(得分:1)

设法使用两个变量来执行此操作,而不会打印超出范围的数字。抱歉,这很糟糕,这是我编程的第一天:)

    int x = 0;
    int y = 1;

    do
    {
        System.out.println(x);
        y = x + y;
        if (y < 100)
        {
            System.out.println(y);
        }
        x = x + y;
    } while (x < 100);

答案 2 :(得分:0)

这应该是你的解决方案

public static void main(String[] args) {

     int prevVal = 1;
     int prevPrevVal = 0;
     int n = 0;
     do{
         int currVal = prevVal + prevPrevVal;
         prevPrevVal = prevVal;
         prevVal = currVal;
         System.out.print(currVal+" ");
         n++;
     }while(n<5);//n is the number of terms


}

答案 3 :(得分:0)

你走了:

int prevVal = 1;
int prevPrevVal = 0;
        do{
        int currVal = prevVal + prevPrevVal;
                    //currVal is your Fibonacc seq.
        prevPrevVal = prevVal;
        prevVal = currVal;
    }
    while(yourCondition);

答案 4 :(得分:0)

使用documentation中的do-while循环的基本结构:

do {
    statement(s)
} while (expression);

您在“语句”部分中想要的是通过每次迭代增加(并可能输出)您的结果。使用do-while循环的基本Fibonacci序列如下所示:

int prevVal = 1;
int prevPrevVal = 0;
int currVal;
do {
    // Add the two numbers
    currVal = prevVal + prevPrevVal;
    // "Bump" up prevPrevVal to prevVal, and prevVal to currVal
    prevPrevVal = prevVal;
    prevVal = currVal;
    // Output to the screen
    System.out.println(currval + "\n");
} while(expression);

答案 5 :(得分:0)

由于您希望Fibonacci的条款最多为100,因此只需将while (prevVal <= 100);更改为while (prevVal+prevPrevVal <= 100);

这将打印最多89个。