Chad wrote:

> (E-Mail Removed) wrote:

> > Chad wrote:

> > > The question is related to the following lines of code:

> > >

> > > #include <stdio.h>

> > > #include <math.h>

> > >

> > > int main(void) {

> > >

> > > int a = (int)pow(2.0 ,32.0);

> > > double b = pow(2.0 , 32.0);

> > >

> > > printf("The value of a is: %u\n",a);

> > > printf("The value of b is: %0.0f\n",b);

> > > printf("The value of int is: %d\n", sizeof(int));

> > > printf("The value of double is: %d\n", sizeof(double));

> > >

> > > return 0;

> > > }

> > >

> > > The output is:

> > >

> > > $./pw

> > > The value of a is: 2147483648

> > > The value of b is: 4294967296

> > > The value of int is: 4

> > > The value of double is: 8

> > >

> > >

> > > The value of 'a' (on my machine) is 2147483648 or 2^31. Is this anyway

> > > related to the fact that 1 int in this case is 32 bits? I

> > >

> >

> > Try unsigned int. Unless this is a simple test code, for the sizes the

> > numbers you are handling I'd recommend long long.

>

> Okay, I tried this. I also forgot to use %lu vs %u.

>

> #include <stdio.h>

> #include <math.h>

>

> int main(void) {

>

> unsigned int a = (unsigned int)pow(2.0 ,32.0);

> double b = pow(2.0 , 32.0);

>

> printf("The value of a is: %lu\n",a);

> printf("The value of b is: %0.0f\n",b);

> printf("The value of int is: %d\n", sizeof(int));

> printf("The value of double is: %d\n", sizeof(double));

>

> return 0;

> }

>

> $./pw

> The value of a is: 0

> The value of b is: 4294967296

> The value of int is: 4

> The value of double is: 8

>

> Now 'a' is zero! Ahhhhhhhhhhhhh........ I'm even more confused.

>
Ahh... that just means that on your platform an int is 32 bits:

4294967296 = (binary) 100000000000000000000000000000000

which is 33 bits. So when your computer does its calculation, it will

only store 32 of those 33 bits, resulting in:

(binary, first 1 chopped off) 00000000000000000000000000000000

which is zero.

The largest 32bit number is (2^32)-1. Of course, this number can't be

calculated on a 32bit CPU (unless using long long of course) since the

2^32 part will simply result in a zero.

Another interesting experiment to see if your CPU uses 2s complement

arithmetic:

unsigned int a = (int) -1;

printf("The value of a is: %u\n",a);

Anyway, all this is probably a little OT. And my code above is not

strictly portable. The best advice if you really want to be handling

large numbers is to use long long which will give you at least 64 bits.