ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

简单分支与循环应用

2021-03-05 23:51:24  阅读:122  来源: 互联网

标签:case int 循环 应用 printf include day 分支


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循环就是在长代码中不能把初始变量和判断、执行过程代码放在一起,对于代码运行和修改都不太友好。

标签:case,int,循环,应用,printf,include,day,分支
来源: https://blog.51cto.com/15101214/2648782

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有