如何使用For循环制作斐波纳契数列?

时间:2017-04-08 05:56:30

标签: for-loop fibonacci

我已经为While Loop做了准备,但我无法使用For。

我尝试了很多东西。

我试图改变我的while循环,但是我没有成功。我也在网上研究过但所有答案都错了。

3 个答案:

答案 0 :(得分:0)

#include <iostream>
using namespace std;

int main()
{
    int n, t1 = 0, t2 = 1, nextTerm = 0;

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i)
    {
        // Prints the first two terms.
        if(i == 1)
        {
            cout << " " << t1;
            continue;
        }
        if(i == 2)
        {
            cout << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;

        cout << nextTerm << " ";
    }
    return 0;
}

答案 1 :(得分:0)

是的,我们可以使用循环来完成。我尝试使用 Java 语言。

公共类FibonacciSequence {

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

}

注意: n是输入值

示例:

输入:n = 20

输出:0 1 1 2 3 5 8 13

答案 2 :(得分:0)

使用C#

 int count = 4, num1 = 0, num2 = 1;
        Console.WriteLine("Fibonacci Series of " + count + " numbers:");

        for (int i = 1; i <= count; ++i)
        {

            /* On each iteration, we are assigning second number
             * to the first number and assigning the sum of last two
             * numbers to the second number
             */
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
        }
        Console.WriteLine(num1 + " ");