Re: Post ur C/C++ Programs Here
aditya.shevade said:
I don't think that the 40th number might be above integer range.
Yes its odd, an int actually displays numbers even upto the 47th Fibonacci value
A sample output from the program below:
Code:
38: 24157817
39: 39088169
[B]40: 63245986[/B]
41: 102334155
42: 165580141
43: 267914296
44: 433494437
45: 701408733
46: 1134903170
47: 1836311903
48: -1323752223 (Goes wrong here onwards)
All this through an Integer variable whose max size is supposed to be
32768?! Or is it some kind of a clever compiler behavior, etc?
Here's the code which did the above:
Code:
#include<iostream>
using namespace std;
int main()
{
int prev=0, fib=0, final=1;
cout<<"1: "<<prev<<endl<<"2: "<<final<<endl;
for(int i=0;i<=97;i++)
{
fib=final+prev;
prev = final;
final = fib;
cout<<i+3<<": "<<fib<<endl;
}
cout<<endl<<"Final: "<<fib<<endl;
return 0;
}
Doing the same with float yeilds right values upto 100, which would be the obvious way to do so correctly:
Code:
#include<iostream>
using namespace std;
int main()
{
float prev=0, fib=0, final=1;
cout.precision(30);
cout<<"1: "<<prev<<endl<<"2: "<<final<<endl;
for(int i=0;i<=97;i++)
{
fib=final+prev;
prev = final;
final = fib;
cout<<i+3<<": "<<fib<<endl;
}
cout<<endl<<"Final: "<<fib<<endl;
return 0;
}
Oddly, using long int results in the same execution as int itself, with numbers crapping out at 48th value and above.