DISCLAIMER: the following Blog post involves computer programming. If this sort of thing bores you or confuses you, you might as well not read any further and instead I advise you to check out something nonsensical like LOLCATS. I wouldn't want to ruin your interweb experience.
---------------------------------------------------------------------
I was wondering how difficult it would be to write a program that would calculate the fibonacci sequence. After giving it a bit of thought, I decided that it didn't seem too hard, so I wrote the program using C++ and compiled the code using Dev C++.
The code seems simple enough. It looks like this:
#include iostream
#include stdlib.h
using namespace std;
int main(){
int first, second, num1,num2,num3;
int index=1;
first=1;
second=1;
do{
num1=first;
num2=second;
num3=num1+num2;
cout<< num1 <<" ";
index++;
first=num2;
second=num3;
}while(index<=45);
cin.get();
return 0;
}
Unfortunately.... things didn't go EXACTLY as planned....
If the 'do loop' is executed 'while(index<=45);' , everything goes according to plan:
But if I start putting in larger numbers, like 'while(index<=65);' BAD things start to happen:
This is quite unfortunate, because I was really hoping to see the hundredth fibonacci number. I can't explain why, I just really had my heart set on it.
Low numbers of iterations work PERFECTLY fine, but larger numbers (anything after 46 iterations) will start giving me negative numbers.
If anyone reading this is a programmer, and sees a problem with the logic, please let me know what I did wrong.
oh.... I know it might be the compilers fault, but I'm too lazy to search the web for another free compiler. K THNX BI !11!
it's because int can't hold that high of a number.
ReplyDelete32-bit integers can roughly go from +2Billion to -2Billion
you can use long instead of int or (even better) unsigned long
oh, and what is
ReplyDeletecout<<<" ";
all about? you didn't even cout a variable..
I don't know why it says:
ReplyDeletecout<<<” “;
it's supposed to say:
cout<
It copied wrong somehow.
Jolly well good then.
ReplyDeleteHaha. Every time I copy and paste it, it comes out wrong.
ReplyDeletelet me try this again, but with spaces:
cout<< num1 << " ";
Well... I changed my 'int's to 'long's and nothing changed. They still come out negative after 46 iterations. It made no difference whatsoever.
ReplyDeleteHowever...
After trying 'unsigned long', it works perfectly. I'm gonna make another blog about this, because I'm still a little confused.
[...] A few days ago, I posted a C++ program that I wrote that was supposed to calculate the fibonacci sequence. It worked up to the 46th number, and then things went a little wonky. I started getting negative numbers for some odd reason. (See what happened: HERE) [...]
ReplyDeletepRIwaf vqtnlrcpizqn, [url=http://atuhmqzkgkym.com/]atuhmqzkgkym[/url], [link=http://uswjyrlmqdbv.com/]uswjyrlmqdbv[/link], http://iacaftulymbb.com/
ReplyDelete