我无法让我的开关功能工作
I can't get my switch function to work
问题是将1到10的所有值相加,不包括值3和6,但我不知道为什么我的开关函数没有过滤掉3和6。这是我的代码
#include <iostream>
using namespace std;
int main()
{
int a=1,total=0;
while (a<=10)
{
a++;
switch (a)
{
case 3:
continue;
case 6:
continue;
default:
total = total + a;
}
}
cout << "Sum of the total numbers are " << total << endl;
return 0;
}
如果在while循环的末尾添加以下内容:
cout << "Current total: " << total << " a=" << a << endl;
问题会变得很清楚。你的输出会是这样的:
Current total: 2 a=2
Current total: 6 a=4
Current total: 11 a=5
Current total: 18 a=7
Current total: 26 a=8
Current total: 35 a=9
Current total: 45 a=10
Current total: 56 a=11
Sum of the total numbers are 56
正如你所看到的,它正确地跳过了3和6,但它缺少了1,并添加了11,这是我认为你没有预料到的两件事。
此外,您正在使用continue
。对于switch语句,您希望使用break
来阻止执行当前案例之后的案例。(详细说明一下,我认为continue
会很好,因为我认为它正在做你想要的事情:将控制权转移回while语句。然而,如果a++
在switch语句之后移动,这将不起作用。如果你在0
启动a
,如另一篇文章中所述,将条件更改为a < 10
,那么你可以使用continue
语句而不是break
)
如果您将a++;
移到while循环的末尾并修复continue
语句,我相信它会如您所期望的那样工作。
由于担心我的编辑可能会混淆问题,这里有两种替代方法可以构建代码以获得您想要的结果:
#include <iostream>
using namespace std;
int main()
{
int a=1,total=0;
while (a<=10)
{
switch (a)
{
case 3:
break;
case 6:
break;
default:
total = total + a;
}
a++;
}
cout << "Sum of the total numbers are " << total << endl;
return 0;
}
或
#include <iostream>
using namespace std;
int main()
{
int a=0,total=0;
while (a<10)
{
a++;
switch (a)
{
case 3:
continue;
case 6:
continue;
default:
total = total + a;
}
}
cout << "Sum of the total numbers are " << total << endl;
return 0;
}
您的代码工作正常,您在中心循环中只会犯一些小错误:a从2变为11,而不是从1变为10。应该是这样的:
int a=0, total=0;
while (a < 10)
{
a++;
// rest of code
}
编辑这样我的答案就更完整了。上面的修复将使您的代码正常工作,从而产生正确的结果,但正如@Pete所指出的,continue
不是摆脱switchcase语句的方法。continue
语句直接将您移回while
循环的下一个循环。一个更好更干净的代码是这样的:
int a=0,total=0;
while (a < 10)
{
a++;
switch (a)
{
case 3:
break;
case 6:
break;
default:
total = total + a;
}
// in every case you will get here; even if a==3 or a==6
}
编辑2如果你喜欢让一个从1到10的循环,这也是可能的:
int a=1,total=0;
while (a <= 10)
{
switch (a)
{
case 3:
break;
case 6:
break;
default:
total = total + a;
}
// in every case you will get here; even if a==3 or a==6
a++;
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 既然存在危险,为什么项目要使用-I include开关
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 为什么这个音频包络不能通过开关的情况?
- 如何简化代码并将开关组合成一个功能?
- 自定义开关功能中存在大量神秘错误
- 是C 库中必需的基于预处理器的功能开关
- 包含开关的功能在C 中不扩展内联
- 在开关状态情况下,模板功能内部的不同类型的分配
- 带顺序开关的插入排序功能
- 开关和功能
- 我无法让我的开关功能工作