http://blog.csdn.net/ajioy/article/details/7339527
一个 int 占4个字节,就是32个比特位,所以能表示的范围为-2^31~+2^31-1 2,147,483,647。
若是unsigned int,能表示的范围是0 ~ +2^32-1 4,294,967,295 约43亿,与地球人口还差那么一大段距离(约78亿)
看一段源码:
- #include <iostream>
- #include <math.h>
- using namespace std;
- int main(){
- //4个字节的unsigned int能表示的最大数为2的32次方减1;
- //pow的返回类型是double,需要强制转换成unsigned int
- unsigned int max = static_cast<unsigned int>(pow(2.0,32) - 1);
- //test值为0,验证此方法行不通,原因见附录
- unsigned int test = 1 << 32;
- //max+1就超出了unsigned int的表示范围
- cout << "unsigned int max value:" << max << endl
- << "then max+1:" << max+1 << endl;
- //int能表示的最小负数-2^31
- cout << "int min value:-" << static_cast<int>(pow(2.0,31)) << endl;
- //4个字节的int能表示的最大正数,不过有警告left shift count >= width of type
- cout << "int max value:" << (1 << 31) - 1 << endl;
- //1默认是int型,要把它指定成unsigned int后正确
- cout << "unsigned int max value:" << (1U << 32) - 1 << endl;
- }
运行结果:
unsigned int max value:4294967295
then max+1:0
int min value:-2147483648
int max value:2147483647
unsigned int max value:4294967295
pow(2.0,1000):1.07151e+301