Fibonacci number

Jul 27, 2008 at 12:19pm
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 Jul 27, 2008 at 12:20pm
Jul 27, 2008 at 1:38pm
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 Jul 27, 2008 at 2:28pm
Jul 28, 2008 at 4:12am
Also where do you call the function for the fib() ?
Jul 28, 2008 at 6:10am
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 Jul 28, 2008 at 6:13am
Jul 28, 2008 at 7:50am
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
(...)
Jul 28, 2008 at 11:42am
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;
}


Jul 29, 2008 at 4:18am
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 Jul 29, 2008 at 4:20am
Jul 29, 2008 at 6:03am
It's OK, but main function should return a value.
return 0; between lines 15 and 16.
Of course recursion is much more slowly !
Jul 29, 2008 at 2:42pm
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
Jul 29, 2008 at 9:54pm
pet:
main() has an implicit return. That means you don't need a return statement.
Jul 30, 2008 at 6:32am
QWERTYman:
I said "should", not "must".There is a difference.
Topic archived. No new replies allowed.