zoukankan      html  css  js  c++  java
  • C++ 无符号整型和整型的区别

      在Win 7系统中,short 表示的范围为 - 32767到 32767,而无符号的short表示的范围为0 到 65535,其他类型的同理可推导出来,当然,仅当数字不为负的时候才使用无符号类型。

      有些事情,当时接触的时候模模糊糊,可是,当你在过些时间慢慢的回头看他时,觉得顿然开悟。

      下面的程序显示了如何使用无符号类型,并说明了程序试图超越整型的限制时所产生的后果。在编写程序时切记不要超越这些类型所限制的范围,否则很难找出问题。

    #include<iostream>
    #define ZERO 0
    using namespace std;
    #include<climits>
    int main()
    {   
        short nu1 = SHRT_MAX;
        unsigned short nu2 = nu1;
        cout << "nu1 has " << nu1 << " and nu2 has " << nu2 << endl;
        cout << "如果每个数都加一呢?" << endl;
        nu1 = nu1 + 1;
        nu2 = nu2 + 1;
        cout << "Now nu1 has " << nu1 << " and nu2 has " << nu2 << endl<<endl;
        nu1 = ZERO;
        nu2 = ZERO;
        cout << "nu1 has " << nu1 << " and nu2 has " << nu2 << endl;
        cout << "如果每个数减一呢?" << endl;
        nu1 = nu1 - 1;
        nu2 = nu2 - 1;
        cout << "Now nu1 has " << nu1 << " and nu2 has " << nu2 << endl;
        cin.get();
        return 0;
    }  

    程序运行结果:  

      nu1 has 32767 and nu2 has 32767
      如果每个数都加一呢?
      Now nu1 has -32768 and nu2 has 32768

      nu1 has 0 and nu2 has 0
      如果每个数减一呢?
      Now nu1 has -1 and nu2 has 65535

      

  • 相关阅读:
    如何引用webservice
    oracle TNS 无法启动 解决方案
    android 照相
    Nutch 运行错误
    XML Bitmap
    Level List
    hadoop hdfs 上传下载文件
    Layer List
    android popup
    [置顶] Clean Talk
  • 原文地址:https://www.cnblogs.com/carlber/p/9845463.html
Copyright © 2011-2022 走看看