簡體   English   中英

我的遞歸斐波那契程序有什么問題?

[英]What is wrong with my recursive fibonacci program?

我不確定我的邏輯是什么錯。 樣本輸出:

How many terms of the Fibonacci Sequence do you wish to compute?
1
1
1
--How many terms of the Fibonacci Sequence do you wish to compute?
5
5
5
5
5
5
5

為什么這樣做呢?

    // Recursive Fibonacci Sequence
#include <iostream>
using namespace std;

double fib(double number);

int main(void) {
        double number;
        cout << "How many terms of the Fibonacci Sequence do you wish to compute?" << endl;
        cin >> number;

        for(int i = 0; i <= number; ++i)
                cout << fib(number) << endl;
} // end main

// function fib definition
double fib(double number) {
        if((number == 0) || (number == 1))
                return number;
        else
                return fib(number - 1) + fib(number - 2);
} // end function fib

看一下你的循環:

for(int i = 0; i <= number; ++i)
    cout << fib(number) << endl;

請注意,循環主體如何不使用i ...它總是調用fib(number) 將其更改為fib(i)將解決該問題。

(這並不是非常有效,因為每次都會最終重新計算值,但這是另一回事。雖然您可以將打印內容放入fib ,但混合了“如何處理結果”和“計算結果”的問題。斐波那契數列”。)

做了:

for(int i = 0; i <= number; ++i)
    cout << fib(i) << endl;

您應該只將“ i”作為for循環中的參數而不是“ number”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM