题目
1 1) #include 2 2) #include 3 3) using namespace std;4 4) int main()5 5) {6 6) unsigned short us = 65535;7 7) us = us + 1;8 8) cout << " unsigned short:";9 9) cout << setw(8) << hex << us<< "," << setw(8) << dec << us << endl;10 10) signed short ss = 32767;11 11) ss = ss + 1;12 12) cout << " signed short:";13 13) cout << setw(8) << hex << ss<< "," << setw(8) << dec << ss << endl;14 14) return 0;15 15) }16<|im_end|>6.把程序第6行修改为unsigned short us=-2,执行该程序,屏幕输出第一行为:A. unsigned short: ffff, -1B. unsigned short: -1, ffffC. unsigned short: ffff, 65535D. unsigned short: 65535, fff
1 1) #include
2 2) #include
3 3) using namespace std;
4 4) int main()
5 5) {
6 6) unsigned short us = 65535;
7 7) us = us + 1;
8 8) cout << " unsigned short:";
9 9) cout << setw(8) << hex << us
<< "," << setw(8) << dec << us << endl;
10 10) signed short ss = 32767;
11 11) ss = ss + 1;
12 12) cout << " signed short:";
13 13) cout << setw(8) << hex << ss
<< "," << setw(8) << dec << ss << endl;
14 14) return 0;
15 15) }
16
<|im_end|>
6.把程序第6行修改为unsigned short us=-2,执行该程序,屏幕输出第一行为:
A. unsigned short: ffff, -1
B. unsigned short: -1, ffff
C. unsigned short: ffff, 65535
D. unsigned short: 65535, fff
题目解答
答案
将`unsigned short us = -2;`赋值后,`us`实际为`65534`。执行`us = us + 1;`后,`us`变为`65535`。
- 十六进制输出:`65535`对应`ffff`。
- 十进制输出:`65535`保持不变。
- `setw(8)`确保输出宽度为8,最终结果为:
```
unsigned short: ffff, 65535
```
答案:C. unsigned short: ffff, 65535
解析
本题主要考查无符号短整型(unsigned short short)和有符号短整型(signed short)的运算规则以及不同,以及cout输出流中setw、hex、dec的使用。解题思路如下:
- 对于无符号短整型变量
us:- 首先,将
-2赋值给无符号短整型变量us。在计算机中是以补码形式存储的。在16位系统中,有符号数-2的补码计算过程为:- 原码:
1000 0000 0000 0010 - 反码:原码除符号位外取反,得到
1111 1111 1111 1101 - 补码:反码加1,得到
1111 1111 1111 1110,转换为十进制就是65534。
- 原码:
- 然后执行
us = us + 1;,即65534 + 1 = 65535。 - 接着使用
cout输出,hexhex表示以十六进制形式输出,65535转换为十六进制为ffff;dec表示以十进制形式输出,65535保持不变。setw(8)是设置输出宽度为8。 2.对于有符号短整型变量ss`: - 初始值
ss = 32767,执行ss = ss + 1;,由于有符号短整型的范围是-32768到32767,32767 + 1会发生溢出,结果变为-32768。 - 同样使用
cout输出,hex和dec分别以十六进制和十进制输出,-32768的十六进制为8000,十进制为-32768。
- 首先,将