首页  >  文章  >  后端开发  >  在C/C++中使用范围在switch case中

在C/C++中使用范围在switch case中

王林
王林转载
2023-09-01 12:09:021628浏览

在C/C++中使用范围在switch case中

在 C 或 C++ 中,我们使用了 switch-case 语句。在 switch 语句中,我们传递一些值,并使用不同的情况,我们可以检查该值。在这里我们将看到我们可以在 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

以上是在C/C++中使用范围在switch case中的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除