zoukankan      html  css  js  c++  java
  • special situation——两个short型变量相加超出short的表示范围

      short型所能表示的数的个数为(32位机器):2^16 = 65536。若为unsigned short表示范围为:0到65535。若为有符号的,表示范围为:-32768到32767,当为32767时,符号位为0,其余15位为1;当为-32767时,符号位为1,其余15位为1;因为是有符号数,所以有正0和负0之分,负零用于表示-32768。

      下面是一段测试程序,通过输出结果可以看出这个special situation的处理情况。

     1 #include <iostream>
     2 #include <fstream>
     3 #include <cstdlib>
     4 
     5 using namespace std;
     6 int main(int argc, char *argv[])
     7 {
     8     short s1 = 32767;
     9     short s2 = 1;
    10     cout << "s1 = " << s1
    11          << " s2 = " << s2
    12          << endl;
    13     short sum = s1 + s2;
    14     cout << "Sum of s1 and s2 is " << sum << endl;
    15 
    16     s1 = sum - s2;
    17     cout << "Is s1 is as the old value? s1 = " << s1 << endl;
    18     system("pause");
    19     return 0;
    20 }
    21 

    s1=32767

     

    s1=32768

     

    s1=32769 

     

     s1=32770

     

    如果不明白的话,可以参考这个随笔“原码、反码、补码,计算机中负数的表示http://www.cnblogs.com/younes/archive/2009/11/13/1602253.html 

  • 相关阅读:
    文本字符集转换
    添加HP消息队列
    fedora19/opensuse13.1 配置svn client
    前端html---介绍前端,标签,列表
    数据分析1
    项目流程
    git 使用
    mongo基础
    linux上面pycharm汉化
    pythonNet 09协程
  • 原文地址:https://www.cnblogs.com/younes/p/1629236.html
Copyright © 2011-2022 走看看