|
From: Abhijit S. <mu...@gm...> - 2002-06-15 17:18:28
|
int is, by default, signed, so one bit of your (signed) int variable (of
size 32 bits) is used to denote sign (+ve means 0, -ve means 1). 31 bits are
left, so, in effect, your int can hold from -((2**31) + 1) to +(2**31) where
** denotes exponentiation... in normal numbers, from -2147483648 to
+2147483647. The value of +2147483648 cannot be stored in the (signed) int.
It wraps around, and becomes the negative extreme. Dissect the bit-codes for
the numbers for more clarity.
The problem can be solved by using an unsigned int, which can hold a value
from 0 to +((2**32) - 1), i.e., 4294967295.
Changed code:
-----------------------------Start Code---------
#include <iostream>
#include <cstdlib>
using namespace std;
typedef unsigned int uint;
uint Power(int a, int n);
int main()
{
int a=2, n=30; // int limit == 4294967295;
// Power(2,30)==1073741824
// Power(2,31)==2147483648
// Power(2,32)==4294967296 out of limit =>
Power(2,32)==0
cout << "Power(" << a << "," << n << ")= " << Power(a,n) << endl;
cout << "Power(" << a << "," << n+1 << ")= " << Power(a,n+1) << endl;
system("PAUSE");
return 0;
}
uint Power(int a, int n)
{
int i=1;
uint r=1;
for (i=1;i<=n;i++)
{
r=r*a;
}
return r;
}
-------------------------------End Code---------
Hope this helps.
--------------------------
http://mudeth.tripod.com
----- Original Message -----
From: "Jose Gana" <jg...@ho...>
To: <dev...@li...>
Sent: Saturday, June 15, 2002 8:59 PM
Subject: [Dev-C++] weird result
> Hi!
> Sorry if it is too obvious!
> I am new in C++. I got 2^30= Power(2,30)= - 2147483648 in stead of +
2147483648 in my program.
>
> I must have done something wrong. But I can figure it out. Can somebody
help me out?
> [program follows]
|