在 C/C++ 中使用 switch case 中的范围
在 C 或 C++ 中,我们已经使用了 switch-case 语句。在 switch 语句中,我们传递一些值,并使用不同的 case,我们可以检查该值。这里我们将看到,我们可以在 case 语句中使用范围。
在 Case 中使用范围的语法如下 −
case low … high
在编写 case 后,我们必须首先写出较低值,然后留一个空格,然后写三个点,再留一个空格,最后写出较高值。
在下面的程序中,我们将看到基于范围的 case 语句的输出是什么。
示例
#include <stdio.h>
main() {
int data[10] = { 5, 4, 10, 25, 60, 47, 23, 80, 14, 11};
int i;
for(i = 0; i < 10; i++) {
switch (data[i]) {
case 1 ... 10:
printf("%d in range 1 to 10\n", data[i]);
break;
case 11 ... 20:
printf("%d in range 11 to 20\n", data[i]);
break;
case 21 ... 30:
printf("%d in range 21 to 30\n", data[i]);
break;
case 31 ... 40:
printf("%d in range 31 to 40\n", data[i]);
break;
default:
printf("%d Exceeds the range\n", data[i]);
break;
}
}
}输出
5 in range 1 to 10 4 in range 1 to 10 10 in range 1 to 10 25 in range 21 to 30 60 Exceeds the range 47 Exceeds the range 23 in range 21 to 30 80 Exceeds the range 14 in range 11 to 20 11 in range 11 to 20
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP