Fibonacci Program

Apr 30, 2013 at 10:11pm
Hello. Today I am working on a project in which I have to make a program that can solve and print the first twenty numbers of a fibonacci sequence.
I do not want the code for a finished program, just some commands and such that can help me finish.
TL;DR: I need some commands to solve an equation.
Apr 30, 2013 at 10:19pm
Once you have the formula, it's trivial to write a working program:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cmath>

int main()
{
    double phi = (1 + std::sqrt(5))/2;
    for(int n = 1; n <= 20; ++n) {
        unsigned int fib = std::pow(phi, n)/sqrt(5) + 0.5;
        std::cout << fib << '\n';
    }
}

online demo: http://ideone.com/hLsoWY
Apr 30, 2013 at 10:19pm
Fibonacci sequence is fun!

1, 1, 2, 3, 5, 8,....

What is so hard?

every iteration you add 2 last number to following number

1+1=2
1+2=3
2+3=5
.
.
.
.
Last edited on Apr 30, 2013 at 10:20pm
Apr 30, 2013 at 10:26pm
No but I am making a program to do that for me, insead of by hand.
Apr 30, 2013 at 10:32pm
This could be simple. You need to use some loops to accomplish this task.
Also, this code is less obfuscated than some of the previous examples given.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
	int original = 0;
	int next = 1;
	int final = 0;
	int amount = 20;

	cout << original << ", ";
	cout << next << ", ";

	for (int i = 0; i < amount; i++)
	{
		final = original + next;
		cout << final << ", ";
		original = next;
		next = final;
	}
	getchar();
	return 0;
}
Last edited on Apr 30, 2013 at 11:02pm
Topic archived. No new replies allowed.