c语言中条件分支语句(待完善)
内容概要
一、if条件语句
二、switch语句
三、else悬挂问题
1、if条件语句
#include <stdio.h> int main(){ char choice; printf("please input a choice:"); //打印提示信息 scanf("%c",&choice); //从标准输入流中截取一个字符(%c是一个字符占位符) if ('a' == choice){ printf("please get in\n"); } else if ('b' == choice){ printf("please get on\n"); } else{ printf("what your say?\n"); } return 0; } // 英语都还给老师了
2、switch语句
#include <stdio.h> int main(){ char choice; char second; printf("please input a choice:"); scanf("%c",&choice); switch(choice){ case 'A':printf("score between 90 and 100\n"); //试者输入A,你会发现所有printf都会被执行 case 'B':printf("score between 80 and 89\n"); case 'C':printf("score between 70 and 79\n"); case 'D':printf("score between 60 and 69\n"); case 'E':printf("you failed to exam!\n"); default : printf("don not proud\n"); } getchar(); // 拿取标准输入流中一个字符,本次拿的是回车键 printf("please input a choice again:"); scanf("%c",&second); switch(second){ case 'A':printf("score between 90 and 100\n");break; //这次输入A,就只有第一个printf被执行了 case 'B':printf("score between 80 and 89\n");break; case 'C':printf("score between 70 and 79\n");break; case 'D':printf("score between 60 and 69\n");break; case 'E':printf("you failed to exam!\n");break; default : printf("don not proud\n"); } }
-与if条件判断不同,
1、switch条件语句中的case条件分支中的条件只能是 常量或者常量表达式 ,不能是条件表达式(second > 20)等;
2、case语句命中执行其后代码不会跳出条件判断,而是会继续往下执行后续case中的语句,所以case分支更像是标签。要使得只执行其中一个case就退出后续代码,需要在每个case后面加入break语句;
3、default是默认分支,其后不用加参数,case语句中可以没有default条件分支
这部分之后再弄吧!
-关于getchar、scanf、标准输入流
当想要通过c语言与用户进行交互时,需要通过输入设备(可以是键盘)将数据交给内存,cpu从内存中读取数据,执行代码后,再将结果返回给内存,内存交给输出设备,完成交互。
scanf函数
-参数1:要从标准输入流中截取的字符串格式;参数2:存地址,用于存放截到的数据
-功能:通过截取标准输入流中的字符,实现用户交互
-返回值:整形
scanf("%s",&a); 截取字符串,并将它存储到变量a中
#include <stdio.h> int main(){ char first[6]; char other[10]; printf("input first:"); scanf("%c%c_dsb",first); printf("first : %s\n",first); getchar(); printf("input second:"); scanf("%s",&other); printf("other : %s\n",other); return 0; }
//第一次输入ca_dsb发现匹配成功,标准输入流中的数据被全部截取,但发现只有字符c被保存到first中
//
3、else悬挂问题
#include <stdio.h> int main(){ char hasTime,hasRain; printf("hasTime please input Y/N:"); scanf("%c",&hasTime); getchar(); printf("hasRain please input Y/N:"); scanf("%c",&hasRain); if ('Y' == hasTime) if ('Y' == hasRain){ printf("yes"); } else{ printf("not has time\n"); } return 0; } // 先输入Y,再输入N。会打印结果not has time
导致这个问题的原因是,c语言中区别代码块是通过大括号来区分的,而python是通过缩进的方法。
在上面的例子中,唯一的else其实从属于第二个if,而不是第一个if(也就是说如果不加入{}加以区分的话,它将和最近的if搭配)
-else悬挂问题解决
#include <stdio.h> int main(){ char hasTime,hasRain; printf("hasTime please input Y/N:"); scanf("%c",&hasTime); getchar(); printf("hasRain please input Y/N:"); scanf("%c",&hasRain); if ('Y' == hasTime){ if ('Y' == hasRain){ printf("yes"); } } else{ printf("not has time\n"); } return 0; }
***待完善***
本文来自博客园,作者:口乞厂几,转载请注明原文链接:https://www.cnblogs.com/laijianwei/p/14497452.html

浙公网安备 33010602011771号