Tuesday, August 26, 2008

Fibonacci and the C++ conundrum (part deux)

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)

'War&' left me a comment saying that I should change my 'int's (variables assigned as integers) to 'long's (variables assigned as long numbers, which are capable of storing more information), so after changing int's to long's, my output (to 100 iterations) looked like this:



As you can see, I was still getting negative outputs. Not only that, but the numbers were completely wrong. The number after '1134903170' and '1836311903' SHOULD be 2971215073 (which is the two previous numbers added together), INSTEAD, it gives me -1323752223. WTF!?!

I REALLY want to know where these crazy negative numbers are coming from. It's driving me crazy.

I then assigned the variables as 'unsigned long's, which I was advised to do by my good friend 'War&'. That actually solved the problem. My program works PERFECTLY fine now up to as many iterations as I please. Here is the fibonacci sequence up to the 100th number:



Thank you War&!!!

But I'm still curious..... I would think that 'unsigned' would just get rid of the negative sign. So I have two quenstions:

1. Why does 'unsigned long' give me the RIGHT numbers? and
2. Why do I get negative numbers when using 'int' and 'long'?

I will investigate this enigma further. Updates will follow...

1 comment:

  1. yvLHnf ueqwalfoxemz, [url=http://qpydlckkqikb.com/]qpydlckkqikb[/url], [link=http://efceeabodtwa.com/]efceeabodtwa[/link], http://pwnqxamlxoec.com/

    ReplyDelete