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

一个 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.
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值