2012-11-08 42 views
-2

我的代碼有問題。有一個斐波那契函數,我希望你知道是什麼。還有兩個文件:In0201.txt和Out0201.txt。同樣,程序應該從文件「In0201.txt」中獲取值並將結果寫入Out0201.txt。C++中的斐波那契算法 - 遞歸地

有些值正在寫入,而是寫入數字序列(到文件),它寫入一個值,就像它是序列中所有這些數字的總和。有人知道它爲什麼會發生?

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

//Fibonacci 
long double fib(int n) { 
    if(n == 0) 
    { 
     return 0; 
    } 

    if(n == 1) 
    { 
     return 1; 
    } 

    return fib(n-1) + fib(n-2); 
} 

int main() 
{ 
    int a; 
    int tmp; 

    ifstream inputFile("In0201.txt"); 
    if (inputFile.is_open()) { 
     inputFile >> a; 
     cout << "Loaded the value 'n' from file: " << endl; 
     cout << a << " " << endl; 
     inputFile.close(); 
    } 

    ofstream outputFile("Out0201.txt"); 
    if (outputFile.is_open()) { 
     tmp = fib(a); 
     cout << "Fibonacci's sequence number: " << tmp << endl; 
     outputFile << tmp << ", "; 
     outputFile.close(); 
    } 
    return 0; 
} 
+0

但是在發佈中的代碼,不包括它的鏈接。 – Sean

+2

舉例說明您的輸入,實際輸出和預期輸出。目前還不清楚問題是什麼。 – interjay

+1

我不明白。你告訴它在文件中寫入一個數字,並且你不知道爲什麼它會寫入一個數字? – Griwes

回答

2
if (outputFile.is_open()) { 
    tmp = fib(a); 
    cout << "Fibonacci's sequence number: " << tmp << endl; 
    outputFile << tmp << ", "; 
    outputFile.close(); 
} 

此代碼將輸出到文件後跟逗號單個整數。如果要輸出fib(int n)中的每個返回值,則需要重構代碼,以便將要寫入文件的字符串追加到遞歸循環中。

解決方案

long double fib(int n, ofstream &openFile) { 
    if(n == 0) 
    { 
     return 0; 
    } 

    if(n == 1) 
    { 
     openFile<<1<<", "; 
     return 1; 
    } 
    ofstream dummyStream; 
    long double nextFib = fib(n-1, openFile) + fib(n-2, dummyStream); 
    openFile<< nextFib <<", "; 
    return nextFib; 
} 


int main() 
{ 
    int a; 

    ifstream inputFile("In0201.txt"); 
    if (inputFile.is_open()) { 
     inputFile >> a; 
     cout << "Loaded the value 'n' from file: " << endl; 
     cout << a << " " << endl; 
     inputFile.close(); 
    } 

    ofstream outputFile("Out0201.txt"); 
    if (outputFile.is_open()) { 
     outputFile << 0 << ", "; 
     fib(a, outputFile); 
     outputFile.close(); 
    } 
    return 0; 
} 

dummyString目的是因爲他們正在通過調用FIB兩次重複無視一半的結果。

+0

更改代碼會更清楚嗎? :) –

+0

恐怕我不明白你正在尋找什麼輸出,沒有我不能寫代碼來做到這一點。 – Ian

+0

In0201.txt Out0201。txt n = 400 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377 –

0

因爲您正在使用遞歸函數。它計算斐波那契數的總和取決於你的數量從in0201.txt

,則應該更換功能是這樣的:

long double fib(int n, ofstream openFile) { 

if(n == 0) 
{ 
    openFile<<0<<", "; 
    return 0; 
} 

if(n == 1) 
{ 
    openFile<<1<<", "; 
    return 1; 
} 
openFile<< fib(n-1) + fib(n-2)<<", "; 
return fib(n-1) + fib(n-2); 
} 

沒有嚐到它,但這是觀念。

+0

我不確定數字將被添加到流中的順序將會是Maciej想要的。但是,是的,這是需要的想法。 – Ian

+0

錯誤C2660:'fib':函數不帶1個參數 –

+0

由於他改變了定義以同時使用數字和ofstream,所以還必須將遞歸調用改爲fib中的fib。又名'openFile << fib(n-1,openFile)+ fib(n-2,openFile)<<「,」;' –

0

考慮更改線路outputFile << tmp << ", ";

for(int i = 0; i < a; i++) 
    outputFile << fib(i) << ", "; 
outputFile << fib(a) << endl; 

如果要列出序列(如你的問題和代碼暗示)。

+1

如果你想從0到yes的序列,這應該會有訣竅 – Pavenhimself