Problem in adding even-valued fibonacci numbers

I've written the following program..but it prints a garbage value. Why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int n=4000000;

    int fib;
    unsigned int sum=0;
    int a=0, b=1;

    for(int i=0; i<n; i++)
    {
         fib = a + b;

         if(fib%2==0)
            sum+=fib;

         a = b;
         b = fib;
    }

    cout<<sum;

    return 0;
}
What is the maximum value for int and unsigned int in your environment?
The calculated sum is out of range for int and unsigned int in just about ANY environment. The sum is HUGEEEE
Last edited on
Registered users can post here. Sign in or register to post.