2016-10-12 13 views
-4

私は自分のプログラムに苦労しています。新しいフィボナッチ数を出力する必要があります。フィボナッチ数がunsigned intの範囲を超える場合は、プログラムを終了するだけです。さらに、新しい行に "n"のフィボナッチ数を表示する必要があります。ここで"n"(入力)フィボナッチ数を出力するプログラムを作成しようとしています

は、これまでのコードです:だからここ

#include<iostream> 
#include<limits> 

using namespace std; 

int main() 
{ 
    unsigned int n; 

    cout << "Please enter the amount of fibonaccis you would like to compute: " << endl; 
    cin >> n; 

    unsigned int next=1; 
    unsigned int current=0; 
    unsigned int c = current; 
    unsigned int temp; 
    unsigned int counter=1; 

    //This bool returns true as soon as an overflow occurs 
    bool overflow; 

/*This bool checks, whether the newly computed 
    number is bigger than the previous number 
    (which may not be the case if an overflow occurs)*/ 

    bool nextBigger; 



    /*Somehow, I could only handle the first 
    inputs by using "bruteforce". 
    If I tried to combine it with the "main loop", 
    it got all messy. */ 

    if(n==0) 
    { 
    std::cout << "0" << " of " << n << endl; 
    } 

    else if(n==1) 
    { 
    std::cout << "0" << endl << "1 of " << n << endl; 
    } 

    else if(n==2) 
    { 
    std::cout << "0" << endl << "1" << endl << "2 of " << n << endl; 
    } 

    else 
    { /* This for-loop increases (at least it should) a counter 
     by one for each computation of a valid fibonacci number*/ 

     for(counter=1;counter<n;++counter) 
     { 

     overflow = (c > (std::numeric_limits<unsigned int>::max()-temp)); 

     if(!overflow && nextBigger) 
     { 
      cout << next << endl; 

     } 

     else 
     { 
      break; //If overflow or next number < previous number, exit program 
     } 

     temp = next; //temp is storage variable for next 
     c = current; //storage variable for current 
     next += current; //next is being altered: it becomes the new fibonacci number 
     current = temp; //current gets value of temp(value of next before being altered) 
    } 

    nextBigger = (next > current); 

    cout << counter << " of " << n << endl; //Output of how many fibonaccis were computed 
} 

    return 0; 
} 

事です。私はCodeBlocksでプログラミングしました。しかし、私はそれをCodeboardで(割り当てとして)アップロードしようとしました。コードボードでは、突然動作しませんでした。たぶんそれは別のコンパイラと関係があるかもしれませんが、私はこの問題をどのように修正できるのか実際にはわかりません。だから、私は非常に困惑しています。私はヒント、アイデア、修正、またはインスピレーションに非常に感謝しています。あなたのコードを見てみると

(私は初心者ですので、私はコードが理解しやすく読みやすい願っています。私は提案の改善のために開いています。)

+2

エラーメッセージが表示されますか?間違った結果?それ以外の何が正確に動作しないのでしょうか? – deviantfan

+3

あなたは私たちに[* did not work *](http://importblogkit.com/2015/07/does-not-work/)以上のものを与える必要があります。 – Biffen

+1

ようこそスタックオーバーフロー!デバッガを使用してコードをステップ実行する方法を学ぶ必要があるようです。良いデバッガを使用すると、プログラムを1行ずつ実行し、どこからずれているかを確認することができます。これはプログラミングをする場合に不可欠なツールです。詳しい読書:[小さなプログラムをデバッグする方法](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) –

答えて

0

それはif文

if(!overflow && nextBigger) 
    { 
     cout << next << endl; 
    } 
のボディを思わ

は実行されません。たぶん、各ループの繰り返しでoverflowとnextBiggerの値を表示して、何が起きているのかをデバッグすることができます。

関連する問題