v1-v2控制语句if
学习目的:
1.了解顺序语句,分支语句,循环语句
2.掌握if~else语句的使用
控制语句有哪些?
判断成绩的级别
1.输入分数 2.是否合法(分数不能超过总分的范围) 3.评级
#include <stdio.h>
int main(){
int a;
printf(" please input a score:");
scanf(" %d",&a);
return 0;
}
只用if,即只有一个判断范围
#include <stdio.h>
int main(){
float score;//直接用score,可以不用a, 另外是可以使用float类型
printf(" please input a score:");
scanf(" %f",&score);
//判断合法
if(score <0 || score >100){
printf("not in [0,100]\n");
return 0;}
if(score>=90 && score <=100)//这边可以简化一下,因为前一个判断合法的部分就已经帮助我们做了判断,简化成 if(score>=90 )
printf("A-good\n");
return 0;
}
既有if,又有else,退出分数判断用的是return 0,其他的分数判断都是一个套一个循环,所有后括号都写在后面
#include <stdio.h>
int main(){
float score;
printf(" please input a score:");
scanf(" %f",&score);
if(score <0 || score >100){
printf("not in [0,100]\n");
}else{
if(score>=90)
printf("A-excellt\n");
else{
if(score >=70)
printf("B-good");
else{
if(score >=60)
printf("C-OK");
else
printf("D-not pass");
}
}
}
return 0;
}
if('a') a的ASCII值为97
if(x=1)和if(x==1)
= 一个等于号 赋值运算符,是赋值 就是让X等于1
== 两个等于号是逻辑运算符,左右两边的数字相等 类型大小 都要相等
if(x=1) 如果不报语法错误 ,,那么 只要X 和 1 的类型相同 那这条判断语句就永远为 true (指判断左右类型是否相同)
if(x==1) 两个等号, X 和1 类型 和 大小 相等, 那么判断为true 反之 判断 为 false (不仅判读左右类型,也要判读数值大小)
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_46009744/article/details/114691680\
v3-v4 switch语句
default是放置在最后一个case之后
枚举也是整型。(整型包括哪些?有符号的,无符号的,Int型和short,long类型)
enum weekday
{ sun,mon,tue) a;
a=mon; //a就是mon,就是1,跳到case 1
switch(a){
case 1:
printf("1\n");
break;
case 2:
printf("2\n");
break;
case 3:
printf("3\n");
break;
default:
printf("not 1 2 3\n");
}
return 0;
}
switch语句的基本形式
#include <stdio.h>
int main(){
int temp=10;
switch(temp){
case 1:
printf("1\n");
break;
case 2:
printf("2\n");
break;
case 3:
printf("3\n");
break;
default:
printf("not 1 2 3\n");
}
return 0;
}
用代码实现if else 里面的分支语句(自己初步实现的,只是写了一个框架,实际上分数是两位数,要放到case后面的话,还得/10)
#include <stdio.h>
int main(){
float score;
printf("please input a score:");
scanf("%f",&score);
switch(score){
case 1:
printf();
break;
case 2:
printf();
break;
case 3:
printf();
break;
default:
break;
}
return 0;
}
}
#include <stdio.h>
int main(){
float score = 0;
printf("please input a score:");
scanf("%f",score);
if(!(score>=0 && score <=100))
printf("not in [0,100]");
else{
switch((int)score /100){
case 10:
case 9:
printf("A-excellent\n");
break;
case 8:
case 7:
printf("B-good\n");
case 6:
printf("C-OK");
break;
default:
printf("D-not pass"\n);
}
}
}
这个用switch语句去判断分数,判断合法性还是要用if来判断
后面用switch再除以10,得到的数再与10,9,8,7......来比较
然后一个区间的,比如说100分的,和90多分的都输出excellent!这样写是为了节省空间,代码
更加简洁。