学点 C 语言(10): switch 语句

180it 2020-03-05 AM 95℃ 0条

学点 C 语言(10): switch 语句

  1. 常规:

include <stdio.h>

int main(void)
{

int i;
for (i = 0; i < 10; i++) {
    switch (i) {
        case 1:
            printf("%d\n", i);
            break;
        case 3:
            printf("%d\n", i);
            break;
        case 5:
            printf("%d\n", i);
            break;
    default:
        printf("*\n");;
    }
}
getchar();
return 0;

}

  1. 省略 default:

include <stdio.h>

int main(void)
{

int i;
for (i = 0; i < 10; i++) {
    switch (i) {
        case 1:
            printf("%d\n", i);
            break;
        case 3:
            printf("%d\n", i);
            break;
        case 5:
            printf("%d\n", i);
            break;
    }
}
getchar();
return 0;

}

  1. 相同结果:

include <stdio.h>

int main(void)
{

int i;
for (i = 0; i < 10; i++) {
    switch (i) {
        case 1: case 3: case 5:
            printf("%d\n", i);
            break;
        case 4:
            printf("@\n");
            break;
    default:
        printf("*\n");
    }
}
getchar();
return 0;

}

  1. 用于字符:

include <stdio.h>

int main(void)
{

char c;
for (c = 'A'; c <= 'G'; c++) {
    switch (c) {
        case 'A': printf("6\n");
            break;
        case 'B': printf("7\n");
            break;
        case 'C': printf("1\n");
            break;
        case 'D': printf("2\n");
            break;
        case 'E': printf("3\n");
            break;
        case 'F': printf("4\n");
            break;
        case 'G': printf("5\n");
            break;
    }
}
getchar();
return 0;

}

  1. 用于枚举:

include <stdio.h>

int main(void)
{

enum ABCD {AAA,BBB,CCC,DDD} e;

e = CCC;
switch (e) {
    case AAA: printf("%d.AAA\n", e); break;
    case BBB: printf("%d.BBB\n", e); break;
    case CCC: printf("%d.CCC\n", e); break;
    case DDD: printf("%d.DDD\n", e); break;
default:
    ;
}
        
getchar();
return 0;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

学点 C 语言(10): switch 语句