探讨int和unsigned能表示的最大的数和最小的数

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亿)

看一段源码:

  1. #include <iostream>  
  2. #include <math.h>  
  3. using namespace std;  
  4. int main(){  
  5.   
  6.  //4个字节的unsigned int能表示的最大数为2的32次方减1;   
  7.  //pow的返回类型是double,需要强制转换成unsigned int  
  8.   unsigned  int max = static_cast<unsigned int>(pow(2.0,32) - 1);  
  9.   //test值为0,验证此方法行不通,原因见附录  
  10.   unsigned int test = 1 << 32;    
  11.   //max+1就超出了unsigned int的表示范围   
  12.    cout << "unsigned int max value:" << max << endl   
  13.         << "then max+1:" << max+1 << endl;   
  14.     //int能表示的最小负数-2^31  
  15.   cout << "int min value:-" << static_cast<int>(pow(2.0,31)) << endl;  
  16.   //4个字节的int能表示的最大正数,不过有警告left shift count >= width of type   
  17.    cout << "int max value:" << (1 << 31) - 1 << endl;   
  18.    //1默认是int型,要把它指定成unsigned int后正确  
  19.  cout << "unsigned int max value:" << (1U << 32) - 1 << endl;   
  20. }  

运行结果:

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值