CPrimerPlus第6版编程练习答案(已下载)

合集下载

软件工程导论第六章课后答案

软件工程导论第六章课后答案

软件⼯程导论第六章课后答案计算机科学与技术第六章习题答案4、图6.18给出的程序流程图代表⼀个⾮结构化的程序,问:(1)为什么说它是⾮结构化的?(2)设计⼀个等价的结构化程序。

(3)在(2)题的设计中使⽤附加的标志变量flag了吗?若没有,再设计⼀个使⽤flag的程序;若⽤了,再设计⼀个不⽤flag的程序。

图6.18 ⼀个⾮结构化程序答:(1)图⽰程序的循环控制结构有两个出⼝,不符合结构程序的定义,因此是⾮结构化的程序。

(2)设计的等价结构化程序盒图如下所⽰:(3)在第(2)题中没有使⽤标志变量flag,设计使⽤附加的标志变量flag,将上述程序改成等价的结构化程序,如下盒图所⽰:7、某交易所规定给经纪⼈的⼿续费计算⽅法如下:总⼿续费等于基本⼿续费加上与交易中的每股价格和股数有关的附加⼿续费。

如果交易总⾦额少于1000元,则等于⼿续费为交易⾦额的8.4%;如果交易总⾦额在1000元到10000元之间,则基本⼿续费为交易⾦额的5%,再加34元;如果交易总⾦额超过10000元,则基本⼿续费为交易⾦额的4%加上134元。

当每股售价低于14元时,附加⼿续费为基本⼿续费的5%,除⾮买进、卖出的股数不是100的倍数,在这种情况下附加⼿续费为基本⼿续费的9%。

当每股售价在14元到25元之间时,附加⼿续费为基本⼿续费的2%,除⾮交易的股数不是100的倍数,在这种情况下附加⼿续费为基本⼿续费的6%。

当每股售价超过25元时,如果交易的股数零散(即,不是100的倍数),则附加⼿续费为基本⼿续费的4%,否则附加⼿续费为基本⼿续费的1%。

要求:(1)⽤判定表表⽰⼿续费的计算⽅法。

(2)⽤判定树表⽰⼿续费的计算⽅法。

答:(1)⽤判定表表⽰⼿续费的计算⽅法如下所⽰:(2)⽤判定树表⽰⼿续费的计算⽅法如下所⽰:8、画出下列伪码程序的流图,计算它的环形复杂度。

你觉得这个程序的逻辑有什么问题吗?C EXAMPLELOOP:DO WHILE Z>0A=B+1IF A>10THEN X=AELSE Y=ZEND IFIF Y<5THEN PRINT X,YELSE IF Y=2THEN GOTO LOOPELSE C=3END IFEND IFG=H+REND DOIF F>0THEN PRINT GELSE PRINT KEND IFSTOP答:(1)该伪码程序的流程图及程序流图如下:环形复杂度V(G)=流图中的边数-流图中的结点数+2=19-14+2=7 =流图中的区域数=流图中判定结点数⽬+1=6+1=7(2)有问题, 算法中控制最外层循环的变量Z没有初始化,且在该循环内部未出现任何改变Z取值的语句。

C Primer Plus中文版 (第5版) 课后习题答案

C Primer Plus中文版 (第5版) 课后习题答案

编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");}2.编写一个程序输出您的姓名及地址。

#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。

C-primer-plus(第五版)课后编程练习答案(完整)精编版

C-primer-plus(第五版)课后编程练习答案(完整)精编版

7.编写一个程序,程序中要调用名为 one_three()的函数。该函数要在一行中显示单词"one", 再调用 two()函数, 然后再在另一行中显示单词"three"。 函数 two()应该能在一行中显示单词"two"。 main() 函数应该在调用 one_three()函数之前显示短语"starting now:",函数调用之后要显示"done!"o 这样, 最后的输出结果应如下所示: starting now one two three done !
第4章 编程练习
字符串和格式化输入/输出
1.编写一个程序,要求输入名字和姓氏,然后以“名字,姓氏”的格式打印。
#include<stdio.h> int main(void) { char surname[20],firstname[20]; printf("Please input your firstname and surname:"); scanf("%s",firstname); scanf("%s",surname); printf("You are %s,%s.\n",firstname,surname); return(0); }
3.编写一个程序,把您的年龄转换成天数并显示二者的值。不用考虑平年 ( fractional year) 和闰年(leapyear)的问题。
#include<stdio.h> int main(void) { int age=22; printf("Age:%d\n",age); printf("Day:%d\n",age*356); return(0); }

CPrimerPlus第6版中文版勘误表

CPrimerPlus第6版中文版勘误表

注意:下面的勘误中,红色字体为修改后的文字,提请各位读者注意。

第 6 页,” 1.6 语言标准”中的第 3 行,将 1987 年修改为 1978 年。

第 22 页,” 2. main ()函数”中的第 1 行, int main (void ) 后面的分号( ; )删除。

第 24 页,“5. 声明”的第 10 行,也就 是一个变量、函数或其他实体的名称。

第 27 页,图 2.3 中,下划线应该只包含括号中的内容;第 2 段的第 4 行,而不是存储 在 源代码 中的指令。

第 30页,“2.5.4 打印多个值”的第 4行,双引 号后面的第 1 个变量。

第 34页,“2.7.3 程序状态”第 2段的第 4 行,要尽量忠实 于代码来模拟。

第 35页,“2.10 本章小结”第 2段的第 1句,声明 语句为变量指定变量名, 并标识该变量中存 储的数据类型;本页倒数第 2 行,即 检查程序每执行一步后所有变量的值。

第37页,“2.12编程练习”中第1题,把你的名和姓打印在一行……把你的 名和姓分别打印在 两行……把你的 名和姓打印在一行……把示例的内容换成你的 名字。

第 40 页,第 1 行,用于把英 磅常衡盎司转换为… … 第44页,“3.4 C 语言基本数据类型”的第 1句,本节将 详细介绍C 语言的基本属性类型……第 46页,“5. 八进制和十六进制”的第 4句,十六进制数 3的二进制数 是 0011,十六进制数 5 的二进制数 是 0101;“6. 显示八进制和十六进制”的第 1 句,既可以使用 也可以 显示不同进制 的数;将“回忆一下……程序在执行完毕后不会立即关闭执行窗口”放到一个括号里。

第 47页,“2. 使用多种整数类型的原因”第 3句,过去的一台运行 Windows 3.x 的机器上。

第 53 页,图 3.5 下面的第 4 行“上面最后一个例子( printf ( “ ” a \\ is abackslash. ” \n ” ); )” 第 56页,正文的第 2行和第 4行应该分别为 printf ( “me32 = %““d”“\n ”, me32); printf ( “me32 = %d\n ” , me32);第 61 页,“无符号类型”的最后 1 句,相当于 unsigned int (即两者之间添加一个空格 )。

C_primer_plus(第五版)课后编程练习答案(完整)

C_primer_plus(第五版)课后编程练习答案(完整)
第一章 概览 编程练习
1.您刚刚被 MacroMuscle 有限公司(Software for Hard Bodies)聘用。该公司要进入欧洲市场,需 要一个将英寸转换为厘米(1 英寸=2.54 cm)的程序。他们希望建立的该程序可提示用户输入英寸值。您的 工作是定义程序目标并设计该程序(编程过程的第 1 步和第 2 步) 。
int toes_square; toes_add=toes+toes; toes_square=toes*toes; printf("toes=%d\ntoes_add=%d\ntoes_square=%d\n",toes,toes_add,toes_square); return(0); }
6.编写一个能够产生下列输出的程序: Smile ! Smile ! Smile Smile ! Smile ! Smile ! 在程序中定义一个能显示字符串 smile 卜一次的函数,并在需要时使用该函数。
5.编写一个程序,创建一个名为 toes 的整数变量。让程序把 toes 设置为 10。再让程序计算两个 toes 的和以及 toes 的平方。程序应该输出所有的 3 个值,并分别标识它们。
#include<stdio.h> int main(void) { int toes=10; int toes_add;
4.编写一个能够产生下面输出的程序: For he's a jolly good fellow! For he's a jolly good fellow! For he's a jolly good fellow!
Which nobody can deny! 程序中除了 main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次: 另一个用于把最后一行输出一次。

C教程

C教程

C#入门经典第三版清晰版(PDF)面向对象程序设计与VC++实践Visual C++ 案例教程面向对象的理论与C++实践C++到VC++精彩100例(新版)C++实训教程C++实用培训教程Borland C++3.1入门教程高质量程序设计指南 c++/c语言(第三版)《C/C++嵌入式系统编程》英文版C程序设计与错误分析(修订版)钱能C++程序设计第二版数据结构各种算法实现(C++模板)数字信号处理c语言程序集C++ Builder 5 实践与提高C++实践之路C语言学习100例实例程序更多更新(2008年11月3日更新)新编C语言大全Effective C++ 第2版侯捷Turbo C实用高级编程技巧Teach Yourself C++ in One Hour a DayC++参考大全第四版Visual C++编程技巧280例Visual C++ 6.0编程经典博览Visual C++视频_音频开发实用工程案例精选Visual C++ 6.0 实例精通Visual C++ 2005入门经典中文版ArcObjects GIS应用开发—基于C#.NET插图详解C# 2008C#大学教程C#编程语言详解C语言C语言程序设计题典Microsoft编写优质无错C程序秘诀STL轻松入门很基础性的文章(译文)深入浅出MFC C语言库函数速查directshow开发指南及代码网络环境下的C编程技巧及实例自已动手写操作系统C语言大全第4版+源码C.Primer.Plus.PDF C语言程序设计与实践C语言标准与实现C函数浏览数据结构习题与解析(C语言篇)Windows via C/C++数据结构C语言版C语言试题集C语言高级编程及实例部析Advanced C 数据结构与算法分析—C语言描述编程精粹-Microsoft编写优质无错C程序秘诀Turbo C2.0实用大全一本全面的C语言入门教程C plus plus Programming CookbookC程序设计:现代方法C语言参考手册(原书第5版)算法与数据结构c与c++描述数据结构C语言描述C 语言编程精粹经典编程900例(C语言)C程序100例经典C语言教程 C 专业项目实例开发C 语言编程要点C专家编程 C sharp 中对注册表的操作C语言编程宝典大全C语言实例教程1.72 C语言程序基础及应用实例C语言学习和精华文摘经典编程900例(C语言) C语言100例及教程C语言完美演绎C语言实例教程C程序设计培训C语言学习300例C语言图象处理方法实用C语言详解C语言经典编程C语言编程实例C语言程序设计及应用实例C语言核心编程C语言书打包下载C语言程序宝典C语言趣味程序百例精解集成学习环境(C语言) C语言教程C语言数值算法程序大全(第二版)C语言圣经 1.0 《C语言编程宝典》用C实现面向对象C语言常用函数手册C常用算法程序集C语言常用算法源代码C语言高级实用编程技巧C语言学习系统C语言编程技巧程序集C语言最新编程技巧200例C语言技术文章微软C编程精粹C 语言高级程序员编程指南C程序设计:现代方法C++语言Effective C++ Thingking C++经典编程900例(C语言)The C++ Programming Language Special EditionC++语言ISO标准文档高质量C++&C编程指南C++程序设计例解学OpenGL编3D游戏_CAI 白话C++COM 技术内幕——微软组件对象模型C++ Primer中文版Essential C++中文版(全)C++Builder6彻底研究C++Primer习题解答C++.Primer.Plus.PDFC++Primer中文版(第4版)完整版C++ Primer 3rd Edition 中文完美版C++程序开发例题与习题用面向对象方法与C++语言描述叙述讲解C++编程C++ProgrammingLanguageC++ CLI标准说明C++程序设计语言特别版(中文版+英文原版)c++builder6编程实例精讲C++沉思录完整版(中文版)编译器与编译器生成器(C++版C++到VC++精彩100例面向对象程序设计与C++教程C/C++指针经验总结C/C++与数据结构C/C++程序设计导论(第二版)C++ GUI Programming with Qt 4C++ Effective STLc++ neural networks and fuzzyC和C++实务精选 C和指针实用C++编程大全C++小型企业工资管理系统C++多范型设计C++编程艺术C++Builder精彩编程实例集锦Starting Out with C++ Early Objects 5th editionC++ Builder PPT 课件共35章C++ Primer Plus (5th Edition)数据结构的c++伪码实现C++经典教程C++编程金典(第三版) 数据结构的c++伪码实现算法与数据结构c与c++描述C++程序设计例解C++标准程序库自修教程与参考手册C++核心编程技术C和C++代码锦囊C++程序设计教程实验书C++基础知识C++大学基础教程C++大学教程(第二版) C++ Templates 全览C++语言的设计和演化高质量程序设计指南 C++_C语言C++代码设计与重用Inside C++ Object ModelBorland C++ 3.0自学培训教程C++Builder学习大全中文版C++ 入门基础教程经典 C++ 语言教程C&C++深层探索C++和面向对象的数值计算C++Builder自学培训教程C++ 设计新思维经典C++语言教程Borland C++ Builder高级编程经典C++图书下载 1C++编程实例详解高质量C_C++编程指南经典C++图书下载 2C_C++深层探索C++程序设计培训教程C++ 常见问题问与答C_C++程序设计C++程序设计教程C++程序设计讲义C++输入输出流及本地化C++Builder核心program C++ 面向对象多线程编程经典 C++语言教程C++Builder基础进阶嵌入式系统中C的开发C++ Primer 3rd Edition创世纪的C++ Builder教程用 C++ 开发 Web 商用程序C++_Primer_Plus_4th C++Builder30开发指南C++名家对话C++应用编程200例21天学会C++ C++实践之路C++面向对象高效编程C++程序调试实用手册C++bulider参考手册 1.1 C#语言C#应用程序开发全程演练c#2008从入门到精通C#2008和.NET 3.5平台Accelerated C# 2008 Cambridge University Press (Mar2007)OReilly.Designing.Embedded.Hardware.May.2005.eBook-DDU零基础学Visual C# 2005 电子教程Beginning C#2008 DatabasesC#记事本完全手册:C#2.0程序设计详解电子教程完全手册C# 2005+SQL Server数据库与网络开发C#入门经典(第三版) C# in Depth_ What you needDATA STRUCTURES AND ALGORITHMS USING C#C#宝典美国计算机宝典丛书Visual C# 2008 Step by StepC# 2005 NET3.0高级编程(第5版)Pro LINQ Object Relational Mapping in C# 2008C#软件项目开发全程剖析C# 3.0 Unleashed_ With the .NETC#技术揭秘C#高级编程(第三版)数据库入门经典--C#编程篇C#软件项目开发全程剖析C#设计模式C#编程思想精通C#数据库开发C#网络应用编程C#线程手册(英文)C#知识类库C#Web应用程序入门经典C#编程从入门到精通C#类设计手册C# COM+ Programming C#进阶手册C# Primer Plus中文版新一代C#与权威指南C#文档中文版(微软)C# 开发编码规范C#与.NET技术平台实演练C#教程C#深入浅出全接触C#程序员参考手册C#高级编程Design Pattern In C# C#入门经典MS Press Inside C#C#实现的俄罗斯方块程序 C#教程C#实例程序C#高级编程第2版C#.NET中文版Web服务开发基础Windows应用高级编程-C#编程篇C#百例精通C#与程序设计C#与.NET技术平台实战演练C#.NET 开发者手册C#英文手册C#语言参考CSharp程序员参考手册精通C#简体中文版C#.NET编程培训教程C#程序100实例C# 参考手册C# WINDOWS程序设计C#系列教程C#语言规范C# 程序员介绍C# 程序员参考手册VC++语言Visual C++应用技巧与常见问题你问我答vchome_graph Programming Windows with MFC西交大吕军VC++程序设计课程Visual 编程实例Visual.C.实践与提高数据库篇西交大吕军VC++程序设计课程Visual C++高级界面特效制作百例VC知识库5周年精华版数据结构算法:VisualC++6.0程序集Visual C++网络通信编程实用案例精选跟着实例学Visual C++6.0访问数据库绘图制表VC知识库电子杂志41-45期深入浅出MFC简体中文版(附源码)专家门诊 Visual C++开发答疑300问VisualC++网络高级编程Visual C++ 6.0职业技能培训教程Visual C++ /MATLAB图像处理与识别实用案例精选零基础学Visual C++ 电子教程vc++技术内幕第四版(清华版)深入编程内幕——Visual C++最新Visual C++使用手册Programming Visual C++ (5th)Visual C++ 6.0 应用开发教程新编Visual C++6.0教程Visual C++ 6.0 数据库开发技术Visual C++ 编程基础与实践Visual C++开发GIS系统(第2版)C/C++编程精选集锦-关键技术精解分册C/C++编程精选集锦-数据库及图形图像分册Sams.Teach.Yourself.Visual.C.Sharp.200824小时自学VC#2008 2008最新版VC++ 编程指南(CHM)Visual C++串口通信工程开发实例导航精彩C++Builder 6程序设计VC++.NET开发驱动程序详解Visual C++6.0运行库参考手册Visual C++ STL中文版Visual C# 2005从入门到精通练习文件Visual.C++程序设计技巧与实例Visual C++_Turbo C串口通信编程VisualC++6_0编程技巧与实例分析VISUAL C++MFC扩展编程提示Visual C++ 数字图像处理VC++6编程方法VC++与Matlab混合编程的快速实现VC++6.0 运行库参考手册用VC开发CGIVC++编程指南VC++5.0易学活用用VC开发win应用VC++6.0 类库参考手册Visual C++6.0从入门到精通Visual C++ 6-24学时学习教程VC++database编程大全Visual C++ 6.0 教程Visual C++ 6.0 编程实例与技巧VC++6.0培训教程Visual C++ 6.0 开发宝典VC使用大全VC++编程技巧与范例Visual C++ 6.0实例Visual C++ 6.0 程序员指南VC++网络教程VISUAL C++扩展编程实例跟我学 VISUAL C++ 6.0VC++面向对象入门Visual C++6.0高级编程技巧与实例精通VisualC++图像编程VC++扩展编程实例Visual C++ 6.0用户开发手册Visual C++.NET应用编程150例用VC++编写USB接口通信程序疯狂VC技巧集Visual C++ 6.0 高级编程VC++6.0 语言参考手册VC模板库手册Visual C++ 6—24学时学习教程VC++6.0内幕用VC开发Activex Visual C++高级编程技巧与实例Visual C++ 设计WIN32应用程序Visual C++6.0运行库参考手册C视频下载C++语言程序设计视频教学西北工业大学C语言程序设计视频电子科技大学--面向对象C++ 视频教程C语言概述视频共14讲数据库相关电子书专题下载Oracle数据库管理员教程VB编程技术电子书下载ASP/电子书下载Delphi程序设计电子书下载JAVA系列电子书专题下载C/C++系列电子书专题下载。

C_primer_plus(第五版)(完整)

C_primer_plus(第五版)(完整)@第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。

该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。

他们希望建立的该程序可提示用户输入英寸值。

您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。

1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。

输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。

#include<stdio.h>int main(void) //此处不可加;{printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。

不用考虑平年( fractional year)和闰年(leapyear)的问题。

#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。

c语言大一书籍

c语言大一书籍如果你是一名大一学生,正在学习C语言,那么以下这些书籍可能会对你有所帮助:1.《C程序设计语言》(第2版)作者:Brian W. Kernighan, Dennis M. Ritchie这本书是经典中的经典,也是C语言的创始人之一Dennis M. Ritchie所著。

它全面介绍了C语言的基本语法、数据类型、运算符、流程控制、函数、指针等概念和技术,同时提供了大量的编程实例和练习题,适合初学者入门。

2.《C和指针》(第2版)作者:Kenneth A. Reek与《C程序设计语言》不同,这本书更加注重指针的使用和理解。

从基础的指针语法开始,逐步深入地介绍了指针的高级应用,如指针数组、多级指针、函数指针等。

这本书是学习C语言中指针部分的不二之选。

3. 《C Primer Plus》(第6版)作者:Stephen Prata这本书是一本综合性的C语言教材,介绍了C语言的基础知识、标准库、文件操作、内存管理、字符串处理等内容。

除了详细的讲解外,书中还提供了丰富的编程实例和练习题,让读者可以通过实践巩固所学知识。

4. 《深入理解计算机系统》(第3版)作者:Randal E. Bryant, David R. O'Hallaron这本书不是专门讲解C语言的,但是它对于理解计算机系统和程序设计都有很大的帮助。

书中详细介绍了计算机系统的各个层次,包括硬件、汇编语言、操作系统、编译器等,同时还提供了大量的实验和习题,让读者可以深入掌握计算机系统的原理和应用。

总之,如果你想系统地学习C语言,建议你选择以上其中一本或多本书籍进行学习。

同时,也可以结合相关的在线教程和编程实践,加深对C语言的理解和掌握。

2024年6月青少年软件编程Python等级考试试卷三级真题(含答案)

2024年6月青少年软件编程Python等级考试试卷三级真题(含答案)分数:100 题数:38一、单选题(共25题,共50分)。

1.现有一组初始记录无序的数据“5,8,6,3,9,2”,使用Python冒泡排序算法,按从小到大的顺序排列,第一轮排序的结果为()。

标准答案:B。

2.题Python列表l=[9,2,8,6,3,4],采用选择排序进行升序排序,第二轮排序后的结果是()。

标准答案:D。

3.经典的韩信点兵问题出自《孙子算经》,译文为,有一些不清楚数量的物品,如果三个为一组的数剩下两个,如果五个为一组的数剩下三个,如果七个为一组的数剩下两个,问这些物品共有多少个。

解决此问题可以用哪种算法()。

A. 解析算法B. 枚举算法C. 排序算法D. 查找算法标准答案:B。

4.下面程序,说法正确的是()。

标准答案:D。

5.题Python的异常处理try...except...else...finally机制中,以下表述哪项是错误的()。

A. 当碰到错误语句时,try代码块的剩余代码将会被忽略,执行except语句块。

B. 当try语句块正确时,try代码块执行完毕,不执行else语句块,执行finally 语句。

C. 不管try代码块正确与否,finally代码都要执行。

D. 项except程序段中语句可能会被执行,也可能不会被执行。

标准答案:B。

6.十进制数25,转化为二进制数为()。

A. 10011B. 11001C. 11000D. 11011标准答案:B。

7.八进制数30,转化为十进制数为()。

A. 24B. 30C. 64D. 192标准答案:A。

8.十进制数90,转化为十六进制数为()。

标准答案:D。

9.下面转化结果与十六进制数3C不相等的是()。

标准答案:C。

10.用python存储某餐馆菜单信息如下:关于该段程序,下列说法正确的是()。

A. 项menu和price组成了一个二维数组。

B. 该段程序一共输出4行结果。

【C++PrimerPlus】编程练习答案——第15章

【C++PrimerPlus】编程练习答案——第15章 1// chapter15_1_tvremote.h23 #ifndef LEARN_CPP_CHAPTER15_1_TVREMOTE_H4#define LEARN_CPP_CHAPTER15_1_TVREMOTE_H5class Remote;6class Tv {7private:8int state;9int volume;10int maxchannel;11int channel;12int mode;13int input;14public:15 friend class Remote;16enum {OFF, ON};17enum {MinVal, MaxVal = 20};18enum {Antenna, Cable};19enum {TV, DVD};2021 Tv(int s = OFF, int mc = 125) : state(s), volume(5), maxchannel(mc), channel(2), mode(Cable), input(TV) {}22void onoff() {state = (state == ON)? OFF : ON;}23bool ison() const {return state == ON;}24bool volup();25bool voldown();26void chanup();27void chandown();28void set_mode() {mode = (mode == Antenna)? Cable : Antenna;}29void set_input() {input = (input == TV)? DVD : TV;}30void settings() const;31void set_status(Remote & r);32 };3334class Remote {35private:36int mode;37int status; // 常规还是互动模式38public:39 friend class Tv;40enum {Normal, Interacte};4142 Remote(int m = Tv::TV) : mode(m), status(Normal){}43bool volup(Tv & t) {return t.volup();}44bool voldown(Tv & t) {return t.voldown();}45void onoff(Tv & t) {t.onoff();}46void chanup(Tv & t) {t.chanup();}47void chandown(Tv & t) {t.chandown();}48void set_chan(Tv & t, int c) {t.channel = c;}49void set_input(Tv & t) {t.set_input();}50void showstatus() const;51 };525354#endif//LEARN_CPP_CHAPTER15_1_TVREMOTE_H555657// chapter15_1_tvremote.cpp5859 #include "chapter15_1_tvremote.h"60 #include <iostream>6162bool Tv::volup() {63if (volume < MaxVal) {64 ++ volume;65return true;66 }67return false;68 }6970bool Tv::voldown() {71if (volume > MinVal) {72 -- volume;73return true;74 }75return false;76 }7778void Tv::chanup() {79if (channel < maxchannel)80 ++ channel;81else82 channel = 1;83 }8485void Tv::chandown() {86if (channel > 1)87 -- channel;88else89 channel = maxchannel;90 }9192void Tv::settings() const {93using namespace std;94 cout << "TV is " << (state == OFF? "OFF" : "ON") << endl;95if (state == ON) {96 cout << "volume setting = " << volume << endl;97 cout << "channel setting = " << channel << endl;98 cout << "mode = " << (mode == Antenna? "antenna" : "cable") << endl;99 cout << "input = " << (input == TV? "TV" : "DVD") << endl;100 }101 }102103void Tv::set_status(Remote &r) {104if (state == ON)105 r.status = r.status == Remote::Interacte? Remote::Normal : Remote::Interacte; 106 }107108void Remote::showstatus() const {109using namespace std;110 cout << "status = " << (status == Interacte? "Interacte" : "Normal") << endl;111 }112113// run114115void ch15_1() {116using namespace std;117 Tv s42;118 cout << "Initial settings for 42\" TV:\n";119 s42.settings();120 s42.onoff();121 s42.chanup();122 s42.chanup();123 cout << "\nAdjusted settings for 42\" TV:\n";124 s42.settings();125126 Remote grey;127 grey.set_chan(s42, 10);128 grey.volup(s42);129 grey.volup(s42);130 cout << "\n42\" settings after using remote:\n";131 s42.settings();132133 Tv s58(Tv::ON);134 s58.set_mode();135 grey.set_chan(s58, 28);136 cout << "\n58\" settings:\n";137 s58.settings();138139 cout << "\n58\" status:\n";140 grey.showstatus();141 s58.set_status(grey);142 grey.showstatus();143 }1// chapter15_2_stdexcept.h23 #ifndef LEARN_CPP_CHAPTER15_2_STDEXCEPT_H4#define LEARN_CPP_CHAPTER15_2_STDEXCEPT_H56 #include <stdexcept>7 #include <cmath>89class meanlogicerr : public std::logic_error {10public:11 meanlogicerr() : logic_error("") {}12const char * what() {return"bad arguments to hmean() or gmean()";}13 };1415#endif//LEARN_CPP_CHAPTER15_2_STDEXCEPT_H1617// run1819double hmean(double a, double b) {20if (a == b)21throw meanlogicerr();22return2.0 * a * b / (a + b);23 }2425double gmean(double a, double b) {26if (a < 0 || b < 0)27throw meanlogicerr();28return std::sqrt(a * b);29 }3031void ch15_2() {32using namespace std;33try {cout << "x = 1, y = 1, hmean = " << hmean(1, 1) << endl;}34catch (meanlogicerr & me) {cout << me.what() << endl;}35try {cout << "x = -1, y = 1, gmean = " << gmean(-1, 1) << endl;}36catch (meanlogicerr & me) {cout << me.what() << endl;}37try {cout << "x = 1, y = 2, hmean = " << hmean(1, 2) << endl;}38catch (meanlogicerr & me) {cout << me.what() << endl;}39try {cout << "x = 1, y = 1, gmean = " << gmean(1, 1) << endl;}40catch (meanlogicerr & me) {cout << me.what() << endl;}41 }1// chapter15_3_meanerr.h23 #ifndef LEARN_CPP_CHAPTER15_3_MEANERR_H4#define LEARN_CPP_CHAPTER15_3_MEANERR_H56 #include <stdexcept>7 #include <iostream>8 #include <string>910class twodouargserr : public std::logic_error {11private:12double arg1;13double arg2;14 std::string funcname;15public:16 twodouargserr(double a1 = 0, double a2 = 0, const char * f = "none")17 : arg1(a1), arg2(a2), funcname(f), std::logic_error("") {}18virtual const char * what() {return"invalid args";}19virtual void msg(){std::cout << funcname << "() logicerr, arg1: " << arg1 << " arg2: " << arg2 << std::endl;} 20 };2122class hmean_err : public twodouargserr {23public:24 hmean_err(double a1 = 0, double a2 = 0, const char * f = "none")25 : twodouargserr(a1, a2, f) {}26virtual const char * what() {return"invalid args";}27virtual void msg(){twodouargserr::msg();}28 };2930class gmean_err : public twodouargserr {31public:32 gmean_err(double a1 = 0, double a2 = 0, const char * f = "none")33 : twodouargserr(a1, a2, f) {}34virtual const char * what() {return"invalid args";}35virtual void msg(){twodouargserr::msg();}36 };373839#endif//LEARN_CPP_CHAPTER15_3_MEANERR_H4041// run4243double hmean2(double a, double b) {44if (a == b)45throw hmean_err(a, b, __func__ );46return2.0 * a * b / (a + b);47 }4849double gmean2(double a, double b) {50if (a < 0 || b < 0)51throw gmean_err(a, b, __func__ );52return std::sqrt(a * b);53 }54void ch15_3() {55using namespace std;56try {cout << "x = 1, y = 1, hmean = " << hmean2(1, 1) << endl;}57catch (hmean_err & he) {cout << he.what() << endl; he.msg();}58try {cout << "x = 1, y = 2, hmean = " << hmean2(1, 2) << endl;}59catch (hmean_err & he) {cout << he.what() << endl; he.msg();}60try {cout << "x = -1, y = 1, gmean = " << gmean2(-1, 1) << endl;}61catch (gmean_err & ge) {cout << ge.what() << endl; ge.msg();}62try {cout << "x = 1, y = 1, hmean = " << gmean2(1, 1) << endl;}63catch (gmean_err & ge) {cout << ge.what() << endl; ge.msg();}64 }剩下的有空写。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter 2 Programming ExercisesPE 2-­‐1/* Programming Exercise 2-1 */#include <stdio.h> intmain(void){ printf("Gustav Mahler\n");printf("Gustav\nMahler\n");printf("Gustav ");printf("Mahler\n"); return 0;}PE 2-­‐3/* Programming Exercise 2-3 */#include <stdio.h> intmain(void){ int ageyears; /* age in years */int agedays; /* age in days *//* large ages may require the long type */ageyears = 101; agedays = 365 * ageyears;printf("An age of %d years is %d days.\n", ageyears, agedays); return 0; }PE 2-­‐4/* Programming Exercise 2-4 */#include <stdio.h> voidjolly(void); voiddeny(void); intmain(void){ jolly();jolly();jolly();deny();return 0; }void jolly(void){printf("For he's a jolly good fellow!\n");}void deny(void){printf("Which nobody can deny!\n");}PE 2-­‐6/* Programming Exercise 2-6 */#include <stdio.h> intmain(void){ int toes;toes = 10;printf("toes = %d\n", toes);printf("Twice toes = %d\n", 2 * toes); printf("toessquared = %d\n", toes * toes); return 0;}/* or create two more variables, set them to 2 * toes and toes * toes */PE 2-­‐8/* Programming Exercise 2-8 */#include <stdio.h> voidone_three(void); voidtwo(void); int main(void){printf("starting now:\n");one_three(); printf("done!\n");return 0;}void one_three(void){printf("one\n"); two();printf("three\n");}void two(void){printf("two\n");}Chapter 3 Programming ExercisesPE 3-­‐2/* Programming Exercise 3-2 */#include <stdio.h> intmain(void){int ascii;printf("Enter an ASCII code: "); scanf("%d",&ascii);printf("%d is the ASCII code for %c.\n", ascii, ascii); return 0; }PE 3-­‐4/* Programming Exercise 3-4 */#include <stdio.h> intmain(void){ float num;printf("Enter a floating-point value: "); scanf("%f", &num);printf("fixed-point notation: %f\n", num);printf("exponential notation: %e\n", num);printf("p notation: %a\n", num); return 0;}PE 3-­‐6/* Programming Exercise 3-6 */#include <stdio.h> intmain(void){float mass_mol = 3.0e-23; /* mass of water molecule in grams */ floatmass_qt = 950; /* mass of quart of water in grams */ float quarts;float molecules;printf("Enter the number of quarts of water: "); scanf("%f",&quarts);molecules = quarts * mass_qt / mass_mol;printf("%f quarts of water contain %e molecules.\n", quarts, molecules); return 0; }Chapter 4 Programming ExercisesPE 4-­‐1/* Programming Exercise 4-1 */#include <stdio.h> intmain(void){ char fname[40];char lname[40];printf("Enter your first name: ");scanf("%s", fname); printf("Enter yourlast name: "); scanf("%s", lname);printf("%s, %s\n", lname, fname); return0;}PE 4-­‐4/* Programming Exercise 4-4 */#include <stdio.h> intmain(void){ float height;char name[40];printf("Enter your height in inches: ");scanf("%f", &height); printf("Enter your name:"); scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return0;}PE 4-­‐7/* Programming Exercise 4-7 */#include <stdio.h>#include <float.h> intmain(void){ float ot_f = 1.0 / 3.0;double ot_d = 1.0 / 3.0;printf(" float values: ");printf("%.4f %.12f %.16f\n", ot_f, ot_f, ot_f); printf("double values: ");printf("%.4f %.12f %.16f\n", ot_d, ot_d, ot_d);printf("FLT_DIG: %d\n", FLT_DIG); printf("DBL_DIG: %d\n",DBL_DIG); return 0;}Chapter 5 Programming ExercisesPE 5-­‐1/* Programming Exercise 5-1 */#include <stdio.h> intmain(void){ const int minperhour = 60;int minutes, hours, mins;printf("Enter the number of minutes to convert: ");scanf("%d", &minutes); while (minutes > 0 ){ hours = minutes / minperhour;mins = minutes % minperhour;printf("%d minutes = %d hours, %d minutes\n", minutes, hours, mins); printf("Enter next minutes value (0 to quit): "); scanf("%d", &minutes);}printf("Bye\n");return0;}PE 5-­‐3/* Programming Exercise 5-3 */#include <stdio.h> intmain(void){ const int daysperweek = 7;int days, weeks, day_rem;printf("Enter the number of days: ");scanf("%d", &days); while (days > 0){ weeks = days / daysperweek;day_rem = days % daysperweek;printf("%d days are %d weeks and %d days.\n",days, weeks, day_rem);printf("Enter the number of days (0 or less to end): "); scanf("%d", &days);}printf("Done!\n"); return0;}PE 5-­‐5/* Programming Exercise 5-5 */ #include<stdio.h>int main(void) /* finds sum of first n integers */{int count, sum;int n;printf("Enter the upper limit: ");scanf("%d", &n); count = 0;sum = 0; while (count++< n) sum = sum + count; printf("sum= %d\n", sum); return 0;}PE 5-­‐7/* Programming Exercise 5-7 */#include <stdio.h> voidshowCube(double x);int main(void) /* finds cube of entered number */{ double val;printf("Enter a floating-point value: ");scanf("%lf", &val); showCube(val);return 0; }void showCube(double x){printf("The cube of %e is %e.\n", x, x*x*x );}Chapter 6 Programming ExercisesPE 6-­‐1/* pe6-1.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include <stdio.h> #define SIZE 26int main( void ) { charlcase[SIZE]; int i; for(i = 0; i < SIZE; i++)lcase[i] = 'a' + i; for (i = 0; i< SIZE; i++) printf("%c",lcase[i]); printf("\n"); return 0;}PE 6-­‐3/* pe6-3.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include <stdio.h> intmain( void ){ char let = 'F';char start; charend;for (end = let; end >= 'A'; end--){for (start = let; start >= end; start--) printf("%c", start); printf("\n");}return 0;}PE 6-­‐6/* pe6-6.c */ #include<stdio.h> int main( void ){ int lower, upper, index;int square, cube;printf("Enter starting integer: ");scanf("%d", &lower); printf("Enter endinginteger: "); scanf("%d", &upper);printf("%5s %10s %15s\n", "num", "square", "cube"); for (index = lower; index <= upper; index++){ square = index * index;cube = index * square;printf("%5d %10d %15d\n", index, square, cube);}return 0;}PE 6-­‐8/* pe6-8.c */ #include<stdio.h> int main( void ){ double n, m;double res;printf("Enter a pair of numbers: ");while (scanf("%lf %lf", &n, &m) == 2){res = (n - m) / (n * m);printf("(%.3g - %.3g)/(%.3g*%.3g) = %.5g\n", n, m, n, m, res);printf("Enter next pair (non-numeric to quit): ");}return 0;}PE 6-­‐11/* pe6-11.c */#include <stdio.h>#define SIZE 8 intmain( void ){ int vals[SIZE];int i;printf("Please enter %d integers.\n", SIZE); for(i = 0; i < SIZE; i++) scanf("%d", &vals[i]);printf("Here, in reverse order, are the values you entered:\n"); for (i =SIZE - 1; i >= 0; i--) printf("%d ", vals[i]); printf("\n"); return 0;}PE 6-­‐13/* pe6-13.c *//* This version starts with the 0 power */#include <stdio.h>#define SIZE 8 intmain( void ){int twopows[SIZE]; inti;int value = 1; /* 2 to the 0 */for (i = 0; i < SIZE; i++){ twopows[i] = value;value *= 2;}i = 0;do {printf("%d ", twopows[i]);i++; } while (i < SIZE);printf("\n");return 0;}PE 6-­‐14/* pe-14.c *//* Programming Exercise 6-14 */#include <stdio.h>#define SIZE 8 intmain(void){ double arr[SIZE];double arr_cumul[SIZE]; inti;printf("Enter %d numbers:\n", SIZE);for (i = 0; i < SIZE; i++){printf("value #%d: ", i + 1);scanf("%lf", &arr[i]); /* or scanf("%lf",arr + i); */}arr_cumul[0] = arr[0]; /* set first element */ for (i = 1;i < SIZE; i++)arr_cumul[i] = arr_cumul[i-1] + arr[i];for (i = 0; i < SIZE; i++)printf("%8g ", arr[i]); printf("\n");for (i = 0; i < SIZE; i++)printf("%8g ", arr_cumul[i]);printf("\n");return 0;}PE 6-­‐16/* pe6-16.c */#include <stdio.h>#define RATE_SIMP 0.10#define RATE_COMP 0.05 #defineINIT_AMT 100.0 int main( void ){double daphne = INIT_AMT;double deidre = INIT_AMT; intyears = 0;while (deidre <= daphne){ daphne += RATE_SIMP * INIT_AMT;deidre += RATE_COMP * deidre;++years; }printf("Investment values after %d years:\n", years);printf("Daphne: $%.2f\n", daphne); printf("Deidre: $%.2f\n", deidre); return 0;}Chapter 7 Programming ExercisesPE 7-­‐1/* Programming Exercise 7-1 */#include <stdio.h> int main(void){ char ch;int sp_ct = 0;int nl_ct = 0;int other = 0;while ((ch =getchar()) != '#'){if (ch == ' ')sp_ct++; else if (ch =='\n') nl_ct++;else other++;}printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other);return 0;}PE 7-­‐3/* Programming Exercise 7-3 */#include <stdio.h> intmain(void){ int n; doublesumeven = 0.0; int ct_even= 0; double sumodd = 0.0;int ct_odd = 0;while (scanf("%d", &n) == 1 && n != 0){if (n % 2 == 0){sumeven += n;++ct_even;}else // n % 2 is either 1 or -1{sumodd += n;++ct_odd;}}printf("Number of evens: %d", ct_even); if(ct_even > 0)printf(" average: %g", sumeven / ct_even);putchar('\n');printf("Number of odds: %d", ct_odd); if(ct_odd > 0)printf(" average: %g", sumodd / ct_odd);putchar('\n'); printf("\ndone\n");return 0;}PE 7-­‐5/* Programming Exercise 7-5 */#include <stdio.h> intmain(void){ char ch;int ct1 = 0;int ct2 = 0;while ((ch =getchar()) != '#'){switch(ch){case '.' : putchar('!');++ct1; break;case '!' : putchar('!');putchar('!'); ++ct2;break; default : putchar(ch);}}printf("%d replacement(s) of . with !\n", ct1); printf("%dreplacement(s) of ! with !!\n", ct2);return 0;}PE 7-­‐7// Programming Exercise 7-7#include <stdio.h>#define BASEPAY 10 // $10 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for 2nd tier #define RATE30.25 // rate for 3rd tier int main(void){double hours;double gross; doublenet; double taxes;printf("Enter the number of hours worked this week: ");scanf("%lf", &hours); if (hours <= BASEHRS) gross = hours* BASEPAY; elsegross = BASEHRS * BASEPAY + (hours - BASEHRS) * BASEPAY * OVERTIME; if (gross <= AMT1) taxes = gross * RATE1; else if (gross <= AMT1 + AMT2)taxes = AMT1 * RATE1 + (gross - AMT1) * RATE2; elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1 - AMT2) * RATE3; net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes, net);return 0;}PE 7-­‐9/* Programming Exercise 7-9 */#include <stdio.h> #include<stdbool.h> int main(void){int limit;int num; intdiv;bool numIsPrime; // use int if stdbool.h not availableprintf("Enter a positive integer: "); while(scanf("%d", &limit) == 1 && limit > 0){if (limit > 1)printf("Here are the prime numbers up through %d\n", limit); elseprintf("No primes.\n"); for(num = 2; num <= limit; num++){for (div = 2, numIsPrime = true; (div * div) <= num; div++)if (num % div == 0) numIsPrime = false; if (numIsPrime)printf("%d is prime.\n", num);}printf("Enter a positive integer (q to quit): ");}printf("Done!\n");return 0;}PE 7-­‐11/* pe7-11.c *//* Programming Exercise 7-11 */#include <stdio.h>#include <ctype.h> intmain(void){const double price_artichokes = 2.05;const double price_beets = 1.15; constdouble price_carrots = 1.09; const doubleDISCOUNT_RATE = 0.05; const double under5 =6.50; const double under20 = 14.00; constdouble base20 = 14.00; const double extralb= 0.50;char ch;double lb_artichokes = 0;double lb_beets = 0; doublelb_carrots = 0; double lb_temp;double lb_total;double cost_artichokes;double cost_beets; doublecost_carrots; doublecost_total; doublefinal_total; double discount;double shipping;printf("Enter a to buy artichokes, b for beets, ");printf("c for carrots, q to quit: "); while ((ch =getchar()) != 'q' && ch != 'Q'){ if (ch == '\n')continue; while (getchar() !='\n') continue; ch =tolower(ch); switch (ch){case 'a' : printf("Enter pounds of artichokes: ");scanf("%lf", &lb_temp); lb_artichokes += lb_temp; break;case 'b' : printf("Enter pounds of beets: ");scanf("%lf", &lb_temp); lb_beets += lb_temp; break;case 'c' : printf("Enter pounds of carrots: ");scanf("%lf", &lb_temp); lb_carrots += lb_temp; break;default : printf("%c is not a valid choice.\n", ch);}printf("Enter a to buy artichokes, b for beets, "); printf("c forcarrots, q to quit: ");}cost_artichokes = price_artichokes * lb_artichokes; cost_beets =price_beets * lb_beets; cost_carrots = price_carrots * lb_carrots;cost_total = cost_artichokes + cost_beets + cost_carrots; lb_total =lb_artichokes + lb_beets + lb_carrots; if (lb_total <= 0)shipping = 0.0; else if (lb_total < 5.0) shipping = under5;else if (lb_total < 20) shipping = under20; elseshipping = base20 + extralb * lb_total; if(cost_total > 100.0)discount = DISCOUNT_RATE * cost_total; elsediscount = 0.0;final_total = cost_total + shipping - discount; printf("Yourorder:\n");printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2f\n",lb_artichokes, price_artichokes, cost_artichokes); printf("%.2f lbs ofbeets at $%.2f per pound: $%.2f\n", lb_beets, price_beets,cost_beets); printf("%.2f lbs of carrots at $%.2f per pound: $%.2f\n",lb_carrots, price_carrots, cost_carrots); printf("Total cost ofvegetables: $%.2f\n", cost_total); if (cost_total > 100)printf("Volume discount: $%.2f\n", discount);printf("Shipping: $%.2f\n", shipping); printf("Totalcharges: $%.2f\n", final_total); return 0; }Chapter 8 Programming ExercisesPE 8-­‐1/* Programming Exercise 8-1 */#include <stdio.h>int main(void) { int ch; int ct =0; while ((ch = getchar()) != EOF)ct++;printf("%d characters read\n", ct);return0;}PE 8-­‐3/* Programming Exercise 8-3 *//* Using ctype.h eliminates need to assume consecutive coding */#include <stdio.h> #include<ctype.h> int main(void){ int ch; unsigned longuct = 0; unsigned long lct= 0; unsigned long oct = 0;while ((ch = getchar()) != EOF)if (isupper(ch)) uct++;else if (islower(ch)) lct++;else oct++;printf("%lu uppercase characters read\n", uct); printf("%lu lowercase characters read\n", lct); printf("%lu other characters read\n", oct);return0;}/* or you could use if (ch >='A' && ch <= 'Z') uct++;else if (ch >= 'a' && ch <= 'z')lct++; else oct++;*/PE 8-­‐5/* Programming Exercise 8-5 *//* binaryguess.c -- an improved number-guesser *//* but relies upon truthful, correct responses */#include <stdio.h> #include <ctype.h>int main(void) { int high = 100;int low = 1; int guess = (high + low) / 2; char response;printf("Pick an integer from 1 to 100. I will try to guess "); printf("it.\nRespond with a y if my guess is right, with"); printf("\na h if it is high, and with an l if it is low.\n"); printf("Uh...is your number %d?\n", guess);while ((response = getchar()) != 'y') /* get response */{if (response == '\n')continue;if (response != 'h' && response != 'l'){printf("I don't understand that response. Please enter h for\n"); printf("high, l for low, or y for correct.\n"); continue;}if (response == 'h')high = guess - 1; else if(response == 'l') low =guess + 1; guess = (high + low)/ 2;printf("Well, then, is it %d?\n", guess);}printf("I knew I could do it!\n"); return 0;}PE 8-­‐7/* Programming Exercise 8-7 */#include <stdio.h>#include <ctype.h>#include <stdio.h>#define BASEPAY1 8.75 // $8.75 per hour#define BASEPAY2 9.33 // $9.33 per hour#define BASEPAY3 10.00 // $10.00 per hour#define BASEPAY4 11.20 // $11.20 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for 2nd tier #defineRATE3 0.25 // rate for 3rd tier intgetfirst(void); void menu(void); int main(void){ double hours;double gross;double net;double taxes;double pay; charresponse;menu();while ((response = getfirst()) != 'q'){if (response == '\n') /* skip over newlines */ continue;response = tolower(response); /* accept A as a, etc. */ switch(response){case 'a': pay = BASEPAY1; break;case 'b': pay = BASEPAY2; break; case 'c':pay = BASEPAY3; break; case 'd': pay = BASEPAY4;break;default : printf("Please enter a, b, c, d, or q.\n");menu();continue; // go to beginning of loop}printf("Enter the number of hours worked this week: ");scanf("%lf", &hours); if (hours <= BASEHRS) gross =hours * pay; elsegross = BASEHRS * pay + (hours - BASEHRS) * pay * OVERTIME; if(gross <= AMT1) taxes = gross * RATE1; else if (gross <= AMT1 +AMT2)taxes = AMT1 * RATE1 + (gross - AMT1) * RATE2; elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1 - AMT2) * RATE3; net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes,net); menu(); }printf("Done.\n");return 0;}void menu(void){printf("********************************************************""*********\n");printf("Enter the letter corresponding to the desired pay rate"" or action:\n");printf("a) $%4.2f/hr b) $%4.2f/hr\n", BASEPAY1,BASEPAY2);printf("c) $%5.2f/hr d) $%5.2f/hr\n", BASEPAY3,BASEPAY4); printf("q) quit\n");printf("********************************************************""*********\n");}int getfirst(void){ int ch;ch = getchar(); while(isspace(ch)) ch =getchar(); while(getchar() != '\n')continue; return ch;}Chapter 9 Programming ExercisesPE 9-­‐1/* Programming Exercise 9-1 */#include <stdio.h>double min(double, double); intmain(void){double x, y; printf("Enter two numbers (qto quit): "); while (scanf("%lf %lf", &x, &y) == 2){ printf("The smaller number is %f.\n", min(x,y)); printf("Next two values (q to quit): ");}printf("Bye!\n");return 0;}double min(double a, double b){return a < b ? a : b;}/* alternative implementation doublemin(double a, double b){ if (a < b)return a; elsereturn b;}*/PE 9-­‐3/* Programming Exercise 9-3 */#include <stdio.h>void chLineRow(char ch, int c, int r); intmain(void){ char ch; int col, row; printf("Entera character (# to quit): "); while ( (ch =getchar()) != '#'){ if (ch =='\n') continue;printf("Enter number of columns and number of rows: "); if (scanf("%d %d", &col, &row) != 2) break; chLineRow(ch, col, row);printf("\nEnter next character (# to quit): ");}printf("Bye!\n");return 0;}// start rows and cols at 0 voidchLineRow(char ch, int c, int r){int col, row;for (row = 0; row < r ; row++){for (col = 0; col < c; col++)putchar(ch); putchar('\n');}return;}PE 9-­‐5/* Programming Exercise 9-5 */#include <stdio.h>void larger_of(double *p1, double *p2); intmain(void){double x, y; printf("Enter two numbers (qto quit): "); while (scanf("%lf %lf", &x, &y) == 2){larger_of(&x, &y);printf("The modified values are %f and %f.\n", x, y); printf("Next two values (q to quit): ");}printf("Bye!\n");return 0;}void larger_of(double *p1, double *p2){ if (*p1 > *p2)*p2 = *p1; else*p1 = *p2;}// alternatively:/*void larger_of(double *p1, double *p2){*p1= *p2 = *p1 > *p2 ? *p1 : *p2;}*/PE 9-­‐8/* Programming Exercise 9-8 */ #include<stdio.h>double power(double a, int b); /* ANSI prototype */ int main(void){ double x, xpow; int n; printf("Enter a number and theinteger power"); printf(" to which\nthe number will be raised.Enter q"); printf(" to quit.\n"); while (scanf("%lf%d", &x, &n)== 2){ xpow = power(x,n); /* function call */printf("%.3g to the power %d is %.5g\n", x, n, xpow);printf("Enter next pair of numbers or q to quit.\n");} printf("Hope you enjoyed this power trip -- bye!\n");return 0;} double power(double a, int b) /* function definition */{ double pow = 1;int i; if (b ==0) { if (a== 0)printf("0 to the 0 undefined; using 1 as the value\n"); pow =1.0; } else if (a == 0) pow = 0.0; else if (b > 0) for(i = 1;i <= b; i++) pow *= a; else /* b < 0 */ pow = 1.0 / power(a, - b);return pow; /* return the value of pow */}PE 9-­‐10/* Programming Exercise 9-10 */ #include <stdio.h>void to_base_n(int x, int base); int main(void){ int number; int b; int count;printf("Enter an integer (q to quit):\n"); while(scanf("%d", &number) == 1){ printf("Enter number base (2-10): ");while ((count = scanf("%d", &b))== 1&& (b < 2 || b > 10)){printf("base should be in the range 2-10: ");} if (count !=1) break;printf("Base %d equivalent: ", b);to_base_n(number, b); putchar('\n');printf("Enter an integer (q to quit):\n");} printf("Done.\n");return 0;}void to_base_n(int x, int base) /* recursive function */{ int r; r = x % base; if(x >= base) to_base_n(x / base,base); putchar('0' + r); return;}Chapter 10 Programming ExercisesPE 10-­‐1/* Programming Exercise 10-1 */#include <stdio.h>#define MONTHS 12 // number of months in a year #defineYRS 5 // number of years of data int main(void){// initializing rainfall data for 2010 - 2014 const floatrain[YRS][MONTHS] = {{4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},{8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}}; int year, month;float subtot, total;printf(" YEAR RAINFALL (inches)\n"); for(year = 0, total = 0; year < YRS; year++){ /* for each year, sum rainfall for each month */ for (month = 0, subtot = 0; month < MONTHS; month++) subtot += *(*(rain+ year) + month); printf("%5d %15.1f\n", 2010 + year, subtot);total += subtot; /* total for all years */}printf("\nThe yearly average is %.1f inches.\n\n", total/YRS); printf("MONTHLY AVERAGES:\n\n");printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct "); printf(" Nov Dec\n");for (month = 0; month < MONTHS; month++){ /* for each month, sum rainfall over years */ for(year = 0, subtot =0; year < YRS; year++) subtot += *(*(rain +year) + month); printf("%4.1f ", subtot/YRS);} printf("\n");return 0;}PE 10-­‐3/* Programming Exercise 10-3 */#include <stdio.h>#define LEN 10int max_arr(const int ar[], int n); voidshow_arr(const int ar[], int n);int main(void){int orig[LEN] = {1,2,3,4,12,6,7,8,9,10}; int max;show_arr(orig, LEN); max = max_arr(orig,LEN); printf("%d = largest value\n", max);return0;}int max_arr(const int ar[], int n){ int i; int max= ar[0];/* don't use 0 as initial max value -- fails if all array values are neg */for (i = 1; i < n; i++)if (max < ar[i]) max= ar[i]; return max;}void show_arr(const int ar[], int n){ int i; for (i = 0;i < n; i++) printf("%d ",ar[i]); putchar('\n');}PE 10-­‐5/* Programming Exercise 10-5 */#include <stdio.h>#define LEN 10double max_diff(const double ar[], int n); voidshow_arr(const double ar[], int n);int main(void){double orig[LEN] = {1.1,2,3,4,12,61.3,7,8,9,10}; double max;show_arr(orig, LEN);max = max_diff(orig, LEN);printf("%g = maximum difference\n", max);return0;}double max_diff(const double ar[], int n){ int i; double max= ar[0]; double min =ar[0];for (i = 1; i < n; i++){if (max < ar[i])max = ar[i]; else if(min > ar[i]) min =ar[i];}return max - min;}void show_arr(const double ar[], int n)。

相关文档
最新文档