[c++]类型转换

例子源于c++ primer

bool b=10; // b is true
bool b=-10;// b is true
bool b=0.0;// b is false
int i=10.2;// i is 10 truncated
int j=-10.2;//j is -10
undigned char c=-1; //assuming 8-bits char, c has value 255  255=-1%256
signed char c2=256; //asuuming 8-bits char, the value of c2 is undefined

unsigned int u=10;int i=-10;
cout<<u+i<<endl;// -10 converted to unsigned int first and then add to u, value is  2^32-10+10
cout<<u-40<<endl;// 
当写for循环依照从大到小的顺序从10递减输出到0时,如果使用unsigned会出问题
for(unsigned int i=10;i>=0;--i)  //因为是unsigned int --i不可能小于0,死循环
    cout<<i<<endl;
一种解决方式是用while
unsigned u=11;
while(u>0)   //0在undigned int 内 可以判断
{--u;
cout<<u<<endl;
}
参照while思路也可以写出for
for(unsigned int i=11;i>0;)
{
--i;
cout<<i<<endl;
}
 

//test
        bool b=-0.0;
        if(b)
        cout<<"b is true"<<endl;
        else 
        cout<<"b is false"<<endl;
        bool a=0e1;
        if(a)
        cout<<"a is true"<<endl;
        else 
        cout<<"a is false"<<endl;
        
        int i=-10.2;
        cout<<"i is "<<i<<endl;
        
        unsigned int u=10,u2=40;
        int t=40;
        
        long long temp=1;
        int times=32;
        while(times>0)
        {
            temp*=2;
            --times;
        }
        
        cout<<"2^32 is "<<temp<<endl;
        cout<<"u10-i40  "<<u-t<<endl;
        cout<<"u10-u40  "<<u-u2<<endl;
        cout<<"-40-u10  "<<-40-u<<endl;




结果:

b is false
a is false
i is -10
2^32 is 4294967296
u10-i40 4294967266
u10-u40 4294967266
-40-u10 4294967246


总结:

1. 如果非bool值赋给bool,如果转换为0(0.0,-0.0,0)则为false,否则是true

2. 如果负数赋给无符号的数,相当于对2^n取余数,n类型的位数决定,char 8 int 32

3. 如果将超过范围的数赋值给带符号的数,结果不确定  比如 int i=2^32; char ch=256;

4. 如果将带符号数与不带符号数混在一起,结果会转换为不带符号数  比如 -40-u10  本来为-50  世纪为2^32-50






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值