c - 切换 vs if ... else if ... else
问题描述
我有个问题。我正在为我的考试而学习,我不知道如何回答这个问题。基本上我必须将指令 if...else if... else 更改为指令开关,以使程序的输出保持不变。
void main()
{
int x;
x = 1;
for (int i = 1; i < 10; ++i) {
if (i <= 3)
do {
x += i;
if (x >= 4)
break;
} while (i % 2 == 0);
else if ((i > 3) && (i < 5))
x += 2;
else
continue;
}
while (x > 0) {
printf(" x=%d ", x);
x -= 1;
}
system("pause");
}
我可以在 for 循环内进行切换吗?
解决方案
当然可以。循环控制语句的for
执行,块就是语句。switch
鉴于它i
在 1 到 9 的包含范围内,您可以将if
块替换为
switch (i){
case 1: case 2: case 3:
// that replaces 'if (i <= 3)'
// ToDo - the code here
break; // to obviate follow-through.
case 4:
// that replaces 'if ((i > 3) && (i < 5))'
// ToDo - the code here
break;
default:
// that replaces 'else'
continue; // note that this is for the for loop, not the switch
}
请注意,此重构不会改变的if (x >= 4) break;
行为。
然而,我不相信if
用 a 替换块switch
是正确的做法:边界i <= 3
和i >= 5
不太自然地用 a 处理switch
;也许改变i
to的类型unsigned
和显式处理case 0:
会在一定程度上缓解这种情况。
推荐阅读
- docker - 为什么 vscode 的远程资源管理器会得到旧容器的列表?(码头工人)
- php - 为什么 Laravel `middleware('auth:sanctum')` 会导致 302 问题?
- docker - Azure Fileshare - 使用 Docker-Compose 将不同的子文件夹/文件挂载到 ACI 上的卷
- python - 如何获取所有值直到某个定义的值以更改 Python Pandas 数据框中的列名称?
- php - php 在 2 个不匹配的数组中查找 id
- ios - 导航视图 - 侧边栏等注释 - 切换按钮
- image - 在 Geopandas 的地图上使用图像作为标记
- pyspark - Pyspark FeatureImportance with RFormula
- node.js - 循环遍历 where 子句中的所有查询参数
- javascript - 使用 jquery 验证电子邮件地址