C 判断 —— switch语句(多个switch值与一组语句联系起来、case顺序是可任意的,default不一定是最后一个case)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42167759/article/details/83586953

一个 switch 语句允许测试一个变量等于多个值时的情况。每个值称为一个 case,且被测试的变量会对每个 switch case 进行检查。

流程图

C 中的 switch 语句

//下面的语句是由用户输入的char变量值来控制
#include <stdio.h>
int main(void)
{
	char answer = 0;
	printf("Enter Y or N:");
	scanf(" %c",&answer);
	
	switch(answer)
	{
//可以把多个case值与一组语句联系起来
		case 'Y':case 'y':
			printf("You responded in the affirmative.\n");
			break;
		case 'N':case 'n':
			printf("You responded in the negative.\n");
			break;
		default:
			printf("You did not respond correctly...\n");
			break;
	}
	return 0;
}

 /*
 * switch语句中的case顺序是可任意的,default不一定是最后一个case
 * */

//输入1-10内的任意数字;各别数字对应对应不同的提示信息,有些数字没有。
#include <stdio.h>
int main()
{
	int choice = 0;
	printf("Pick a number between 1 and 10 and you may win a prize:");
	scanf("%d",&choice);

	if((choice > 10) || (choice < 1))
		choice = 11;
	
	switch(choice)
	{
		case 7:
			printf("You win the collected works of Amos of Amos Gruntfuttock.\n");
			break;
		case 2:
			printf("You win the folding thermomenter-pen-watch-unbrella.\n");
			break;
		case 8:
			printf("You win the lifetime supply of aspirin tablets.\n");
			break;
		case 11:
			printf("Try between 1 and 10.You wasted your guess.\n");
	
		default:
			printf("Sorry,you lose.\n");
			break;
	
	}
	return 0;
}

 执行结果显示如下:

[root@J01051386 Test_20180418]# gcc switch.c 
[root@J01051386 Test_20180418]# ./a.out 
Pick a number between 1 and 10 and you may win a prize:3
Sorry,you lose.
[root@J01051386 Test_20180418]# ./a.out 
Pick a number between 1 and 10 and you may win a prize:7
You win the collected works of Amos of Amos Gruntfuttock.

猜你喜欢

转载自blog.csdn.net/weixin_42167759/article/details/83586953
今日推荐