问题描述
我可能正在寻找一些东西,但是在C ++中是否有一种简单的方法可以将案例分组在一起,而不是将它们单独写出来?我记得基本可以做到:
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:
SELECT CASE Answer
CASE 1, 2, 3, 4
C ++中的示例(对于需要它的人):
Example in C++ (For those that need it):
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1:
case 2:
case 3:
case 4:
cout << "You need more cars. ";
break;
case 5:
case 6:
case 7:
case 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
推荐答案
否,但是您可以使用 if
- else if
- else
链也能达到相同的结果:
No, but you can with an if
-else if
-else
chain which achieves the same result:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
您可能还想通过引发异常来处理0辆汽车的情况,然后还要处理负数汽车的意外情况.
You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.
PS:我将 Answer
重命名为 answer
,因为用大写字母开头的变量被认为是不好的风格.
PS: I've renamed Answer
to answer
as it's considered bad style to start variables with an uppercase letter.
请注意,诸如Python之类的脚本语言允许以[1、2、3、4] 语法提供漂亮的 if答案,这是一种灵活地实现所需内容的方法.
As a side note, scripting languages such as Python allow for the nice
if answer in [1, 2, 3, 4]
syntax which is a flexible way of achieving what you want.
这篇关于将switch语句案例分组在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!