-
Fibonacci in C++
Im actually kinda embarassed to ask this question.
Code:
#include <iostream>
int main() {
unsigned long long a = 1;
unsigned long long b = 1;
for (int i = 0; i < 45; i++) {
a += b;
std::cout << a/b << std::endl;
b += a;
std::cout << b/a << std::endl;
}
std::cin.get();
}
Why cant i get it to work?
-
Re: Fibonacci in C++
What do you expect from your program? What seems to be the problem?
-
Re: Fibonacci in C++
I want to end up with the number 1.618, or something like it, but i have trued everything it seems, it will only print integers, i should
know why, but either i've forgotten how this work (a int working a lotwith float/double) or i am just stupid.
If you remove the /a and /b from the code u'll see that it does indeed work, but those are not the numbers i want.
-
Re: Fibonacci in C++
Here is a recursive algorithm:
Code:
int fibonacci( int i ) {
if ( i == 0 ) return 0;
if ( i == 1 ) return 1;
else return fibonacci( i - 1 ) + fibonacci( i - 2 );
}
And non-recursive:
int fibonacci( int i ) {
int result[] = { 0, 1 };
while ( i > 1 ) {
int t = result[0];
result[0] = result[1];
result[1] = result[0] + t;
--i;
}
return result[i];
}
int main() {
for ( int i = 0; i < 45; ++i )
cout << i << ": " << fibonacci( i ) << '\n';
}
-
Re: Fibonacci in C++
When you divide a integer by an integer, you get an integer. What you want is to convert one of them to double before dividing, like double(a)/b
-
Re: Fibonacci in C++
It seems he wants a series converging (slowly) to the golden ratio, or something like that.
The problem is that he performs an integer division instead of a floating point division.
Here are some ways of forcing a floating point division in C++:
double(a)/b instead of a/b
1.0*a/b instead of a/b
(a+0.0)/b instead of a/b
double a instead of unsigned long long a;
We should note, however, that the above is not a standard C++ program since there is no "long long" type in C++.
C++ does have a "long double" type.
Page generated in 1,717,384,646.35653 seconds with 10 queries