简体   繁体   中英

Fibonacci number

i am writing code that prints determined by user fibonacci number. The problem is that when i type 0, or 1 everything run as i expect whereas as i type 3 or more output of the program is random number(location of result variable in computer memory), please excause me for such easy question, but at work i am coding in VBA, and after switching to C++ i cannot see what is wrong with my code, and i have no one to ask for help because i am self-lerner. Big thanks in advance.

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int f0, f1, a, result;

    f0 = 0;
    f1 = 1;
    cout << "Type number of fibonacci element you want to print\n" << endl;
    cin >> a;

    if (a == 0)
    {
        result = f0;
        cout << "Your result it;\n";
        cout << result;
    }
    if (a == 1)
    {
        result = f1;
        cout << "Your result is";
        cout << result;
    }
    if (a >= 2)
    {
        for (int i = 2; i > a; i++)
            result = f0 + f1;
        f0 = f1;
        f1 = result;

        cout << "Your result is:\n";
        cout << result;
    }

    return 0;
}
for(int i=2;i>a;i++)
result = f0+f1;
f0 = f1;
f1 = result;

Instead this should be like that:

for(int i=2;i<=a;i++){
   result = f0+f1;
   f0 = f1;
   f1 = result;
}

So, firstly: correct use brackets, and secondly: i<=a in place of (i>a) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM