我的逻辑是:如何在C中的switch case语句中使用范围?
if number is between 1 to 10, execute first case statement
if number is from 20 to 30, execute second case statement
有比低于一个其它的解决方案?
case '1' ... '10':
case '20' ... '30':
我的逻辑是:如何在C中的switch case语句中使用范围?
if number is between 1 to 10, execute first case statement
if number is from 20 to 30, execute second case statement
有比低于一个其它的解决方案?
case '1' ... '10':
case '20' ... '30':
选项1:使用case 0
为0-9
,case 1
为11-20
等。
选项2:使用if
选项3:
通过这样的情况下使用秋天另一个破旧方式:
#include <stdio.h>
int main(void) {
int i=1;
for(i=1;i<=25;i++)
{
switch(i)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
printf("%d is in between 1-10\n", i);
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
printf("%d is in between 11-20\n", i);
break;
default:
printf("%d is above 20\n", i);
}
}
return 0;
}
输出:
1 is in between 1-10
2 is in between 1-10
3 is in between 1-10
4 is in between 1-10
5 is in between 1-10
6 is in between 1-10
7 is in between 1-10
8 is in between 1-10
9 is in between 1-10
10 is in between 1-10
11 is in between 11-20
12 is in between 11-20
13 is in between 11-20
14 is in between 11-20
15 is in between 11-20
16 is in between 11-20
17 is in between 11-20
18 is in between 11-20
19 is in between 11-20
20 is in between 11-20
21 is above 20
22 is above 20
23 is above 20
24 is above 20
25 is above 20
谢谢,但如果我必须检查千位数 – user3205621
在这种情况下'switch'可能不是要走的路。 –
如果您必须检查数千个数字,您应该在原始问题中提及该数字。 – abelenky
C不支持除单个整数(或类似整数的东西 - 字符,枚举值)以外的大小写值。所以,你的选择是:
case 1: case 2: case 3: ... case 10: do_something();
if
而非case
。void SwitchDemo(int value)
{
switch(value/10)
{
case 0: ...; break; // 0 - 9
case 1: ...; break; // 10 - 19
...
}
}
,或者特定的问题的范围内:
void SwitchDemo(int value)
{
switch((value-1)/10)
{
case 0: ...; break; // 1 - 10
case 1: ...; break; // 11 - 20
...
}
}
在c交换机语句只能在一个常量表达式操作的情况下语句不能包括动态比较。
Example of something which is, and is not, a "Constant Expression" in C?
对于一些这种简单的if/else结构可以更加清晰和简单,这取决于你的编译器case语句可以被翻译成一系列反正分支比较报表。
'switch()'**可以**操作_expression_部分中的非常量表达式'开关(表情)...' – chux
的GCC编译器支持,作为语言的扩展,case ranges像:
switch(i) {
case 0 ... 9: return true;
default: return false;
}
该语言的扩展也被Clang/LLVM接受。因此,如果您可以负担限制您的代码到GCC & Clang编译器,请使用它。请参阅this。
我不知道为什么这个扩展名不包含在C11标准中。
您将无法在标准C中使用switch-case
声明执行此操作。
(如其他答案已经指出,一些编译器具有非标准的扩展,使这个)
相反,我建议做一个数据结构,如:
struct RangeData
{
int start;
int end;
void (*func)(int);
};
RangeData ranges[] = { { 1, 10, Handle10s },
{ 20, 30, Handle20s },
{5000, 10000, HandleBigNumbers} };
那么它应该是很容易做出循环的小循环,找到适当的范围,并调用正确的功能。
void DoNumber(int value)
{
for(int i=0; i<ARRAYSIZE(ranges); ++i)
{
if (ranges[i].start <= value && value <= ranges[i].end)
{
ranges[i].func(value);
}
}
}
您唯一的选择就是按照您不想或按照pzaenger的建议去做。 – Steve
如果您需要非便携式解决方案,gcc可以使用基于范围的案例。 – Boiethios
你的意思是“1 ... 10”,而不是“1”......“10”。并且该构造是gcc扩展,而不是标准C. –