【考研复习】关于C语言输出溢出问题|关于short i=65535/65536/65537

#include <stdio.h>
using namespace std;
int main()
{
    
    
    short i = 65535;
    printf("%d\n",i);
} // namespace std;

输出结果为-1.
signed short int的取值范围-32768~32767,传入的65535溢出。short int类型截取65535后八位11111111(八个1),首位为1,认定为负数。由于负数在计算机内由补码形式表示,负数的补码为取反加1,最后得到00000001,结果为-1.

#include <stdio.h>
using namespace std;
int main()
{
    
    
    short i = 65535;
    printf("%d\n",i);
} // namespace std;

输出结果为0.
short int类型截取后65536八位00000000(八个0),结果为0.

#include <stdio.h>
using namespace std;
int main()
{
    
    
    short i = 65535;
    printf("%d\n",i);
} // namespace std;

输出结果为1.
short int类型截取后65536八位00000001(七个0),结果为1.

#include <stdio.h>
using namespace std;
int main()
{
    
    
    unsigned short int i = 65535;
    printf("%d\n",i);
} // namespace std;

输出结果为65536.
unsigned short int的取值范围为0-65535


拓展题
下列代码运行结果:

short i = 65537;
int j = i + 1;
printf("i=%d,j=%d\n", i, j);

输出:i=1,j=2
short 无符号表示范围-32768~32767。
当65536用int(四个字节32位)表示为0000 0000 0000 0001 0000 0000 0000 0001,转化为short的时候高两位字节丢失,于是变成1。求j的值是再将i转化为int类型,高位两位字节补0,所以i没有变化,j的值为2。


参考链接
https://blog.csdn.net/jack0201/article/details/75646978
https://www.nowcoder.com/questionTerminal/ad664223e69b4027a6371fe2f3739490

猜你喜欢

转载自blog.csdn.net/m0_52427832/article/details/131130703