




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第4章选择结构C语言大学实用教程南京审计学院计算机科学与技术系孙玉星
1本章学习内容算法的描述方法常用算法(累加累乘、统计、递推迭代、穷举)选择结构及相关控制语句(第四章)循环结构及相关控制语句(第五章)结构化程序设计的基本思想Skill:MapproblemtosolutioninflowchartandpseudocodeformsBeabletodevelopaprogramcontainingselectionandloopcontrolstructureConsiderthefollowing….Problem:
烤蛋糕(BakingaCake)Howtosolve:
Start
将烤箱预热
准备一个盘子
在盘子上抹上一些黄油
将面粉、鸡蛋、糖和香精混合在一起搅拌均匀将搅拌好的面粉团放在盘子上
将盘子放到烤箱内End实际生活中的算法
AlgorithminRealLife‘DivideandConquer’Strategy
(分治策略)inAlgorithmProblem:
准备早餐(PrepareaBreakfast)
1. Start2. 准备早餐3. End1.Start2.准备早餐
2.1准备一个金枪鱼三明治2.2准备一些薯条2.3冲一杯咖啡3.End‘DivideandConquer’Strategy
(分治策略)inAlgorithm1.Start2.准备早餐
2.1准备一个金枪鱼三明治2.1.1拿来两片面包2.1.2准备一些金枪鱼酱
2.2准备一些薯片2.3冲一杯咖啡3.End‘DivideandConquer’Strategy
(分治策略)inAlgorithm1.Start2.准备早餐2.1准备一个金枪鱼三明治2.1.1拿来两片面包2.1.2准备一些金枪鱼酱
2.2准备一些薯片
2.2.1将土豆切成片2.2.2油炸这些土豆片
2.3冲一杯咖啡3.End‘DivideandConquer’Strategy
(分治策略)inAlgorithm‘DivideandConquer’Strategy
(分治策略)inAlgorithm1.Start2.准备早餐2.1准备一个金枪鱼三明治2.1.1拿来两片面包2.1.2准备一些金枪鱼酱
2.2准备一些薯片2.2.1将土豆切成片2.2.2油炸这些土豆片
2.3冲一杯咖啡2.3.1烧些开水放入杯中2.3.2在水杯中加入一些咖啡和糖3.EndWhatistheconnectionbetweenthesereallifeprocessesandalgorithm?Somethingtoponder…算法(Algorithm)的概念
数据结构+算法=程序只对面向过程的语言(C)成立面向对象程序=对象+消息算法:为解决一个具体问题而采取的确定的有限的操作步骤,仅指计算机能执行的算法Aspecificandstep-by-stepsetofinstructionsforcarryingoutaprocedureorsolvingaproblem,usuallywiththerequirementthattheprocedureterminateatsomepoint算法的特性
有穷性在合理的时间内完成确定性,无歧义
如果x≥0,则输出Yes如果x≤0,则输出No有效性
能有效执行负数开平方没有输入或有多个输入
有一个或多个输出
算法的表示方法自然语言描述传统流程图(Flowchart)在1966年,Bohra
与Jacopini
提出N-S结构化流程图1973年,美国学者I.Nassi
和B.Shneiderman
提出伪码(Pseudocode)表示流程图(Flowchart)Flowchartrepresentsalgorithmgraphically.Start/EndSymbolSemanticProcessInput/OutputTestConnectorFlowofactivities问题求解步骤
(ProblemSolvingProcess)InputProcessOutputFirstidentifytheinputandoutputoftheproblem.Example1:买苹果,计算价钱Calculateanddisplaythepriceofanumberofapplesifthequantityinkgandpriceperkgaregiven.
quantity
pricePerkgpriceprice=quantity*pricePerkgInputProcessOutput流程图(Flowchart):
CalculatePriceofApplesInputquantity
Startpricequantity*pricePperkgInputpricePerkgOutputpriceEndIfnecessary,use‘Divide&Conquer’strategytodecomposetheproblemintosmallerandmanageablesubproblems.main(){
scanf("%d",&quantity);
scanf("%d",&pricePerkg);price=quantity*pricePerkg;
printf("%d",price);}CProgram:CalculatePriceofApplesInputquantity
Startpricequantity*pricePperkgInputpricePerkgOutputpriceEndIt’snotcomplete!Declarethevariables…main(){
int
quantity,price_per_kg,price;
scanf("%d",&quantity);
scanf("%d",&pricePerkg);price=quantity*pricePerkg;
printf("%d",price);}CProgram:CalculatePriceofApplesInputquantity
Startpricequantity*pricePperkgInputpricePerkgOutputpriceEndWelldone!But…whatarethey?main(){
int
quantity,price_per_kg,price;
scanf("%d",&quantity);
scanf("%d",&pricePerkg);price=quantity*pricePerkg;
printf("%d",price);}CProgram:CalculatePriceofApplesInputquantity
Startpricequantity*pricePperkgInputpricePerkgOutputpriceEndStartDeclaration}InputProcessOutputEndAnoutlineofaprogram,writteninaformthatcaneasilybeconvertedintorealprogrammingstatements.Itresemblestheactualprogramthatwillbeimplementedlater.However,itcannotbecompilednorexecuted.伪码(Pseudocode)1.Start2.Readquantity3.Readprice_per_kg4.
price
quantity*price_per_kg5.Printprice6.EndPseudocodenormallycodesthefollowingactions:
InitialisationofvariablesAssignmentofvaluestothevariablesArithmeticoperationsRelationaloperations顺序(Sequence)结构的NS图给变量赋值赋值表达式语句
赋值表达式;
price=quantity*pricePerkg;输入输出数据标准库函数调用语句
scanf("%d",&pricePerkg);
printf("%d",price);NS图BAExample2:
CalculatetheMinimum计算两个数中的最小者.
num1num2min????InputProcessOutputABNY条件PBNAY条件P选择结构(分支结构)
(SelectionStructure)NS图传统流程图NoYesFlowchart:CalculatetheMinimumInputnum1Inputnum2Outputminnum1<num2?minnum2minnum1
StartEndscanf("%d%d",&num1,&num2);if(num1<num2)min=num1;elsemin=num2;printf("%d",min);NoYesInputnum1Inputnum2Outputminnum1<num2?minnum2minnum1
StartEndCProgram:CalculatetheMinimummain(){
intnum1,num2,min;
scanf("%d%d",&num1,&num2);
if(num1<num2) min=num1;
else min=num2;
printf("%d",min);}}
SelectionStructureCProgram:CalculatetheMinimumif-elseSingleSelectionDoubleSelectionMultipleSelectionifif–else-if选择结构(分支结构)
(SelectionStructure)单分支选择结构
(SingleSelection)StepaconditionStepmStepnStepbtruefalsestepaconditionstepmstepnstepbtruefalsePseudocodeStructurestepaif<conditionistrue>start stepm stepnend_ifstepbifStatementThestructureissimilartosingleselection(flowchart)Syntax:
if
(expression) statement;or
if
(expression){ statement1; statement2; }复合语句compoundstatement被当作一条语句看待ifStatementThestructureissimilartosingleselection(flowchart)Syntax:
if
(expression) statement;or
if
(expression){ statement1; statement2; }Don’tforgetthebraces
!!Don’tforgettheparentheses
!!if
StatementThesimilaritybetweensingleselectionstructureandif
statement:SingleSelectionPseudocode
:if<conditionistrue>start step1 step2 … stepkend_ifif
Statement:if(expression){ statement1 statement2 … statementk}表达式非0为真ifStatementmain(){
intnum1,num2,min;
printf(“Input2numbers:“);
scanf(“%d%d”,&num1,&num2);min=num1;
if(num1>num2) min=num2;
printf(“Smallest:%d\n”,min);}Input2numbers:_num2?num1?min?Input2
numbers:2015_20152015Input2numbers:2015Smallest:15_20>15?ifStatementExample:main(){
intmark;
scanf(“%d”,&mark); if(mark>=60)
printf(“Pass\n”);
printf(“Yourmarkis%d”,mark);}Whatwilltheoutputbeifthemarkis65?ifStatementExample:main(){
intmark;
scanf(“%d”,&mark); if(mark>=60)
printf(“Pass\n”);
printf(“Yourmarkis%d”,mark);}Whatwilltheoutputbeifthemarkis35?双分支选择结构
(DoubleSelection)PseudocodeStructureStepaif<conditionistrue>start Stepm Stepnend_ifelsestart Stepx Stepyend_elseStepzStepaconditionStepmStepnStepztruefalseStepxStepyStepaconditionStepmStepnStepztruefalseStepxStepyif-else
StatementThestructureissimilartodoubleselection(flowchart)Syntax:
if(expression)
statement;
else
statement;or
if
(expression){ statement1; statement2; }
else
statement3;or
if
(expression)
{ statement1; statement2;}
else
{ statement3; statement4;}if-else
StatementThesimilaritybetweendoubleselectionstructureandif-elsestatement:DoubleSelectionPseudocode:if<conditionistrue>start step1 … stepkend_ifelsestart step1 … stepnend_elseif
Statement:if(expression)
{ statement1 … statementk}else{ statement1 … statementn}if-elseStatementExample:if(num1<num2) min=num1;else min=num2;printf(“Smallest:%d\n”,min);num215num110min?10<15?_10Smallest:10_if-elseStatementExample:if(num1<num2) min=num1;else min=num2;printf(“Smallest:%d\n”,min);num215num120min?20<15?_15Smallest:15_if-elseStatementif(num1<num2){ min=num1; max=num2;}else{ min=num2; max=num1;}printf(“Min=%d,Max=%d\n”,min,max);num2125num1700min??700<125?_max??Min=125,Max=700_125700条件运算符计算最小值if(num1<num2) min=num1;else min=num2;printf(“Smallest:%d\n”,min);min=num1<num2
?
num1
:num2;printf(“Smallest:%d\n”,min);表达式1?表达式2:表达式3习题4.24.2选择题(1)在下面的条件语句中,只有一个在功能上与其他三个语句不等价,这个不等价的语句是
A)if(a)s1;elses2;B)if(!a)s2;elses1;C)if(a!=0)s1;elses2;D)if(a==0)s1;elses2;Let’srecap…SingleSelectionStatement stepa
if
(expression){ stepm stepn } stepbSingleSelectionLet’srecap…PseudocodeStructure stepa if<conditionistrue>start stepm stepn end_if stepbSingleSelectionDoubleSelectionStatement
stepa
if(expression){ stepm stepn }
else
{ stepx stepy } stepbDoubleSelectionGuess…howdoesmultipleselectionlooklike?多分支选择结构(MultipleSelection)Multi-wayifStepaif
(expression1){ Stepm}if
(expression2)
{ Stepn}StepzStepaexpression1StepmStepnStepztruefalseexpression2truefalseStepaexpression1StepmStepnStepztruefalseexpression2truefalse多分支选择结构(MultipleSelection)CascadedifStepaif
(expression1){ Stepm}elseif(expression2){ Stepn}
else
{ Stepx}StepzStepaexpression1StepmStepnStepztruefalseexpression2truefalseStepxStepaexpression1StepmStepnStepztruefalseexpression2truefalseStepxCascadedifStepaif
(表达式1){Step1}elseif(表达式2){Step2}elseif(表达式3){Step3}elseif(…){Step…}
else
{Stepn}Stepzexpr1step1非0=0expr2expr3StepnStep3Step2非0非0=0=0StepaStepz…例4.5:体型判断按“体指数”对肥胖程度进行划分:
体指数t=w/h2
(体重w单位为公斤,身高h单位为米)当t<18时,为低体重;当18≤t<25时,为正常体重;当25<t<27时,为超重体重;当t≥27时,为肥胖。编程从键盘输入你的身高h和体重w,判断你的体重属于何种类型。例4.5#include<stdio.h>main(){
floath,w,t; printf("Pleaseenterh,w:"); scanf("%f,%f",&h,&w); t=w/(h*h);
if(t<18) { printf("t=%f\tLowerweight!\n",t); }
if(t>=18&&t<25) { printf("t=%f\tStandardweight!\n",t); }
if(t>=25&&t<27) { printf("t=%f\tHigherweight!\n",t); }
if(t>=27) { printf("t=%f\tToofat!\n",t); }}当t<18时,为低体重;当18≤t<25时,为正常体重;当25<t<27时,为超重体重;当t≥27时,为肥胖。#include<stdio.h>main(){
floath,w,t; printf("Pleaseenterh,w:"); scanf("%f,%f",&h,&w); t=w/(h*h);
if(t<18)
printf("t=%f\tLowerweight!\n",t);
elseif(t<25) printf("t=%f\tStandardweight!\n",t);
elseif(t<27)
printf("t=%f\tHigherweight!\n",t);
else
printf("t=%f\tToofat!\n",t);}182527例4.5当t<18时,为低体重;当18≤t<25时,为正常体重;当25<t<27时,为超重体重;当t≥27时,为肥胖。if语句的嵌套if
(p1)
if(p2)A
elseBelse
if(p4)C
elseDif
(p1)Aelse
if(p2)C
elseDif
(p1)
if(p2)A
elseBelse
C
if
(p1)
if(p2)Aelseif(p4)C
elseDif
(p1)
if(p2)AelseC
else与哪个if配套?{}{}多路选择(switch)
and
break
Thestructureissimilartomultipleselection(flowchart)switch(expression){
case
value1:
statement1; break;
case
value2:
statement2; break;
…
default:
statementX; break;}Don’tforgetthebraces!!Don’tforgetthecolons!!Don’tforgettheblank!!
ImportantRule!!switch(expression){
case
value1:
statement1; break;
case
value2:
statement2; break;
…
default:
statementX; break;}Mustbeintorchar!多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”); break; case3:
printf(“March\n”); break; default:
printf(“Others\n”); break; }
printf(“End”);Assumemonth=1,so……thisstepwillbeexecuted.Later……caseisterminatedhere.Jumpto…January_JanuaryEnd_多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”); break; case3:
printf(“March\n”); break; default:
printf(“Others\n”); break; }
printf(“End”);…thisstepwillbeexecuted.Later…March_MarchEnd_Assumemonth=3,so……caseisterminatedhere.Jumpto…多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”); break; case3:
printf(“March\n”); break; default:
printf(“Others\n”); break;}
printf(“End”);Now…whatwillhappenifthisbreakistakenoutfromtheprogram?多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”);
case3:
printf(“March\n”); break; default:
printf(“Others\n”); break; }
printf(“End”);Nomore!!多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”);
case3:
printf(“March\n”); break; default:
printf(“Others\n”); break; }
printf(“End”);…thisstepwillbeexecuted.Later…February_March_Assumemonth=2,so……caseisterminatedhere.Jumpto…End_…executioncontinues.Thus,thisstepisexecuted.So…多路选择(switch)
and
break
Example:switch(month){ case1:
printf(“January\n”); break; case2:
printf(“February\n”);
case3:
printf(“March\n”); break; default:
printf(“Others\n”); break;}
printf(“End”);Now…whatwillhappenifthesebreaksaretakenoutfromtheprogram?And…ifmonth=1?And…ifmonth=34?多路选择(switch)
and
break
最好不省略4.2(2)设有声明语句inta=1,b=0;,则执行以下语句后输出结果为
。
switch(a){case1:switch(b){case0:printf("**0**");break;case1:printf("**1**");break;}case2:printf("**2**");break;}A)**0** B)**0****2** C)**0****1****2** D)有语法错误例4.8:计算器程序编程设计一个简单的计算器程序,要求根据用户从键盘输入如下形式的表达式:操作数1运算符op操作数2
然后,计算并输出表达式的值指定的运算符为 加(+) 减(-) 乘(*) 除(/)
main(){
intdata1,data2;/*定义两个操作符*/
charop;/*定义运算符*/ printf("Pleaseentertheexpression:"); scanf("%d%c%d",&data1,&op,&data2);/*输入运算表达式*/
switch(op) {
case'+':/*处理加法*/ printf("%d+%d=%d\n",data1,data2,data1+data2);
break;
case'-':/*处理减法*/ printf("%d-%d=%d\n",data1,data2,data1-data2);
break;
case'*':
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 合肥市期末八上数学试卷
- 广西桂平期末数学试卷
- 海南高考一模数学试卷
- 城乡要素双向流动-洞察及研究
- 客户反馈机制与满意度动态-洞察及研究
- 河西联考数学试卷
- 区块链技术应用分析-第1篇-洞察及研究
- 广东中考揭阳数学试卷
- 海淀高二数学试卷
- 嘉积中学二模数学试卷
- JGJ106-2014 建筑基桩检测技术规范
- 2023年中国石化河北石家庄石油分公司社会招聘20人笔试模拟试题及答案解析
- 太阳能热水系统设计
- 医务科岗前培训
- 共青团团课主题班会课件PPT模板PPT
- GB/T 8685-2008纺织品维护标签规范符号法
- 合成氨行业发展现状及趋势分析
- 2022年徐闻县(中小学、幼儿园)教师招聘笔试试题及答案解析
- 网电部管理重点(中)
- 新生儿复苏解析课件
- ABI7500荧光定量PCR仪标准操作规程
评论
0/150
提交评论