c++程序设计实践教程课本题目。实验二 基本数据处理2_1
调试示例,有三个变量a,b,c,定义及赋值如下,请正确输出它们的原值,其数据类型的定义是否正确?
#include<iostream>
void main()
{
short int a = 65535;
unsigned int b = -8;
long int c = 12.34;
cout << "a= " << a << endl;
cout << "b= " << b << endl;
cout << "c= " << c << endl;
}
期望的运行结果为:
a= 65535;
b= -8;
c= 12.34;
这道题考的是short int 、unsigned int 、long int类型的范围。
二话不说跑去百度了一下:https://blog.youkuaiyun.com/u012372584/article/details/77824218
自己也在自己的机子上运行了链接了的程序,发现64位机子也是一样。
即short int 的范围为 -32768~32767。显然上面的题目 a= -1。
分析:
65535存储内容的二进制格式为1111 1111 1111 1111,这个值传给short int类型的 a变量,因为首位为1,故此值是负数,然后反码加1, 0000 0000 0000 0000 +1 => 1,即a =-1
同理, 可以算一下-8的机器码:
高位1,绝对值8的原码为 0000 0000 0000 0000 0000 0000 0000 1000
反码,1111 1111 1111 1111 1111 1111 1111 0111
+1得到机器码: 1111 1111 1111 1111 1111 1111 1111 1000
因为是无符号类型的,所以b = 4294967288 (我直接算2的32次方减去8)
long int 是整型,小数值直接过滤掉了。
要想得到预期的输出,可以按照以下代码更改:
#include<iostream>
void main()
{
int a = 65535; // 或者unsigned short int a = 65535;
int b = -8;
double c = 12.34; // 或者float c = 12.34f;
cout << "a= " << a <<endl;
cout << "b= " << b <<endl;
cout << "c= " << c <<endl;
}