zoukankan      html  css  js  c++  java
  • 34 char类型转换为int类型

    #include<iostream>
    #include<cstdlib >
    using namespace std;
     
    int main() {
             char a=101;
             int sum=200;
             a+=27;sum+=a;
             printf("%d", a);
             cout<<sum<<endl;
    }
    

      

    分析:char类型的范围是-128---+127,当a+=27,之后a的值超出可表示范围会变为-128.

    a为char型,-128~127,a=101,a+=27后溢出a=-128:

    a=127时不溢出 01111111(127补码)

    a+=1时溢出 10000000(-128补码)

     

    sum += a;

    sum为int型,a(char提升为int)

    10000000------->11111111  11111111  11111111  10000000(-128补码)

    所以,sum=200-128:00000000  00000000 00000000  11001000

    +11111111 11111111  11111111 10000000

    ----------------------------------------------------------------------------------

     00000000  00000000  00000000  01001000  (64+8=72)

     



    char c=128; printf("c=%d ",c); 结果为什么是-128,请解释为什么?

    因为有符号字符型其范围为-128~127,127用二进制表示为:0111 1111,128表示为1000 0000,这里发生溢出,因为第一位为1,为符号位,表示负数,即-128

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    toj 2975 Encription
    poj 1797 Heavy Transportation
    toj 2971 Rotating Numbers
    zoj 2281 Way to Freedom
    toj 2483 Nasty Hacks
    toj 2972 MOVING DHAKA
    toj 2696 Collecting Beepers
    toj 2970 Hackle Number
    toj 2485 Card Tric
    js页面定位,相关几个属性
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7472668.html
Copyright © 2011-2022 走看看