您的位置:首页 > 其它

简单分支与循环应用

2021-03-05 23:28 736 查看

1、今天把学习一周的分支选择和循环结构简单的写一些代码来巩固自己一周的学习,也从中 反思和再领悟。
2、分支选择结构可用if和switch两种语句实现。以下是两种语句的例子。
switch语句的实现
#include <stdio.h>
#include <stdlib.h>

/ run this program using the console pauser or add your own getch, system("pause") or input loop /

int main(int argc, char *argv[])
{
int day=0;
scanf("%d",&day);
switch(day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("工作日\n");
break;
case 6:
case 7:
printf("休息日\n");
break;
default :
printf("输入错误\n");
break;
}
return 0;
}

if语句实现的例子
#include <stdio.h>
#include <stdlib.h>

/ run this program using the console pauser or add your own getch, system("pause") or input loop /

int main()
{
int day=0;
scanf("请输入周天数%d",&day);
if(day<=5)
printf("今天是工作日\n");
else if(day==6)
printf("今天是休息日\n");
else if(day==7)
printf("今天是休息日\n");
else
printf("输入错误\n");
return 0;
}

3、循环结构常使用while和for语句,以下是两种循环事例:
for循环
#include <stdio.h>
#include <stdlib.h>

/ run this program using the console pauser or add your own getch, system("pause") or input loop /

int main(int argc, char *argv[])
{
int i;
for(i=0;i<100;i++)
{
if(i%2==1) //或者使用 i+=2;也能实现
printf("%d\n",i);
}
i++;

return 0;

}

while循环事例
#include <stdio.h>
#include <stdlib.h>

/ run this program using the console pauser or add your own getch, system("pause") or input loop /

int main()
{
int ch;
while((ch=getchar())!=EOF)
{
if(ch>='0'||ch<='9')
putchar(ch);
}
return 0;
}
分支结构和循环结构学后体会:使用多种结构能快速地实现数据地处理,用简单的代码处理复杂的问题,使问题简化。在使用getchar()输入中了解到输入数据中存在空白缓冲区,设计循环分支程序时需要仔细考虑,并发现while同for循环存在一定的缺点:while循环就是在长代码中不能把初始变量和判断、执行过程代码放在一起,对于代码运行和修改都不太友好。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: