Fibonacci number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <iostream>

using namespace std;
int n;
int fib();
int main()
{
cout << n << endl;
}
int fib()
{
  if(n=0)return 0;
  if(n=1)return 1;
  if(n>1)return n>1;
  else return n=n-1+n-2; 
  return n;
}

I want to get first 10 Fibonacci numbers , but something is wrong in this program , need help.
Last edited on
First of all correct the operators
= is assignment operator
we use it to assign a value to a variable
 
int x=5;

== is equality operator
we use it to check something equal to someOtherThing
 
if(n==1)


Still your prgram may not work, 'n' is not initialized any where.

Last edited on
Also where do you call the function for the fib() ?
May be it look better!

int main()
{
cout << n << endl;
fib(n);
}

int fib(int n)
{
if(n=0)return 0;
if(n=1)return 1;
if(n>1)return n>1;
else return n=n-1+n-2;
return n;
}

Enjoy !
Last edited on
Your calculation of the Fibanacci-numbers is wrong.

They are not calculateted as n= n+1 + n+2

The next Fibanacci number is the sum of the previous nuber and the one previous to that.
So, in terms of c++ Fib_num[n]=Fib_num[n-1]+Fib_num[n-2] with:
Fib_num[1] =Fib_num[2] = 1

I hope, that helps solve the problem.

int main

you should get:
1
1
2
3
5
8
13
21
34
55
89
(...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int fib(int n)
{
  if(1 == n || 2 == n)
  {
      return 1;
  }
  else
  {
      return fib(n-1) + fib(n-2);
  }

}

int main()
{
    for(int i=1; i<=10; i++)
    {
        cout << fib(i) << endl;
    }
    return 0;
}


This is how I did mine. hehe. A little different but it's very straight forward.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main(){
	int input(0), Alpha(0), Beta(1), Total(1);  
	cout << "Please input a top number: "; 
	cin >> input; 
	
	for(int i = 0; i <= input; i++){
	cout << Total << endl; 
	Total = Alpha + Beta; 
	Alpha = Beta;
	Beta = Total; 
	}//for
}//main 
Last edited on
It's OK, but main function should return a value.
return 0; between lines 15 and 16.
Of course recursion is much more slowly !
In some cases it is slower. This explains nicely recursion is not always the best way to do something.

http://cis.stvincent.edu/html/tutorials/swd/recur/recur.html
pet:
main() has an implicit return. That means you don't need a return statement.
QWERTYman:
I said "should", not "must".There is a difference.
Topic archived. No new replies allowed.