题目
以下程序的输出结果是: #include <iostream.h>int main(){ int x=3,y=3; switch(x%2) { case 1: switch (y) { case 0: cout<<"first"; case 1: cout<<"second"; break; default: cout<<"hello"; } case 2: cout<<"third"; } return 0;}A. second thirdB. helloC. first secondD. hellothird
以下程序的输出结果是:
#include <iostream.h>
int main()
{
int x=3,y=3;
switch(x%2)
{
case 1:
switch (y)
{
case 0:
cout<<"first";
case 1:
cout<<"second";
break;
default:
cout<<"hello";
}
case 2:
cout<<"third";
}
return 0;
}- A. second third
- B. hello
- C. first second
- D. hellothird
题目解答
答案
D
解析
本题考查嵌套switch语句的执行流程,关键在于理解switch-case的匹配规则和无break时的通断现象。外层switch的条件为x%2,当x=3时,余数为1,匹配外层case 1。此时进入内层switch,y=3不匹配case 0或case 1,触发default输出hello。由于内层switch无break,执行完default后,外层switch的case 1代码块结束,继续执行后续的case 2,输出third。最终输出结果为hellothird。
外层switch分析
x=3,x%2=1,匹配外层case 1。- 执行内层switch语句:
y=3,不匹配case 0和case 1,触发default,输出hello。- 内层switch无break,执行完毕后,回到外层switch的
case 1代码块末尾。
- 外层
case 1无break,继续执行后续的case 2,输出third。
输出结果
内层switch输出hello,外层switch后续输出third,合并为hellothird,对应选项D。