一、打招呼
要求根据用户输入的不同数字,程序作出简单回应
例如
用户输入1,系统回应 早安
用户输入2,系统回应 午安
用户输入3,系统回应 晚安
用户输入4,系统回应 再见
用户输入其他,系统回应 啊 你说什么
1、代码
1.1if else 级联代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int type;
scanf("%d",&type);
if (type==1){
printf("早安");
}
else if (type==2){
printf("午安");
}
else if (type==3){
printf("晚安");
}
else if (type==4){
printf("再见");
}
else{
printf("啊,什么呀");
}
return 0;
}
1.2 多路分支代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int type;
scanf("%d",&type);
switch (type){
case 1 :
printf("早安");
break;
case 2 :
printf("午安");
break;
case 3 :
printf("晚安");
break;
case 4 :
printf("再见");
break;
default :
printf("啊,你说什么呀");
break;
}
return 0;
}
注意事项
//注意switch case 语句里type只适用于整数型
//default 是当你输入的数值不符时,程序输出的内容
2、代码及运行结果

二、成绩转换
1、要求

2、代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int grade;
printf("请输入1到100的分数:");
scanf("%d",&grade);
grade/=10;
switch (grade){
case 10:
case 9:
printf("A\n");
break;
case 8:
printf("B\n");
break;
case 7:
printf("C\n");
break;
case 6:
printf("D\n");
break;
default:
printf("E\n");
break;
}
return 0;
}
3、代码及运行结果

本文通过两个实例展示了C语言中if-else级联和switch-case结构的应用:一是根据用户输入数字进行问候;二是将百分制成绩转换为等级评定。
787

被折叠的 条评论
为什么被折叠?



