C++程序设计(第2版)第二章习题解答

合集下载

c程序设计语言(第2版新版)习题解答

c程序设计语言(第2版新版)习题解答

c程序设计语言(第2版新版)习题解答C程序设计语言(第2版新版)是计算机编程领域的经典教材,由Brian W. Kernighan和Dennis M. Ritchie共同编写,后者也是C语言的共同发明者。

这本书不仅介绍了C语言的基本语法和编程技巧,还包括了丰富的习题,帮助读者更好地理解和掌握C语言。

以下是对书中部分习题的解答。

第1章引言习题1-1:编写一个C程序,打印出“Hello, World!”。

```c#include <stdio.h>int main() {printf("Hello, World!\n");return 0;}```习题1-2:修改上述程序,使其打印出不同的字符串。

```c#include <stdio.h>int main() {printf("Welcome to C Programming!\n");return 0;}```第2章数据类型及其运算习题2-1:编写一个程序,计算两个整数的和,并打印结果。

```c#include <stdio.h>int main() {int a, b, sum;a = 5;b = 10;sum = a + b;printf("The sum of %d and %d is %d\n", a, b, sum);return 0;}```习题2-2:编写一个程序,计算两个浮点数的乘积。

```c#include <stdio.h>int main() {float x, y, product;x = 3.14159;y = 2.718;product = x * y;printf("The product of %.5f and %.5f is %.5f\n", x, y,product);return 0;}```第3章控制语句习题3-1:编写一个程序,打印从1到10的整数。

c语言程序设计教程第二版课后习题答案

c语言程序设计教程第二版课后习题答案

c语言程序设计教程第二版课后习题答案【篇一:c语言程序设计教程_李含光_郑关胜_清华大学出版社习题答案习题答案[完美打印版]】1.单项选择题(1)a (2)c(3)d (4)c (5)b 2.填空题(1)函数(2)主函数(main)(3)printf() , scanf()第2章习题参考答案1.单项选择题1-5 cbccc 6-10 cdcdc 11-13 dbb 2.填空题(1)1(2)26 (3)6 , 4 , 2 (4)10 , 6(5)3.000000 (6)双精度(double)(7)9 (8)字母,数字,下划线(9)13.700000 (10)11(11)((m/10)%10)*100+(m/100)*10+m%10(12)0 (13)10 ,9 ,11(15)(x0y0)||(x0z0)||(y0||z0)(16)double (17)x==0(18)sqrt(fabs(a-b))/(3*(a+b))(19)sqrt((x*x+y*y)/(a+b))第3章习题参考答案1.单项选择题1-5 cccdd 6-10 bcdbc11-15 bcbbb16 a 2.填空题(1)用;表示结束(2){ }(3)y=x0?1:x==0?0:-1(4)y%4==0y%100!=0||y%400==0(5)上面未配对(6)default 标号(7)while , do while , for(8)do while(9)本次(10)本层 3.阅读程序,指出结果(1)yes(2)*(3)abother(4)28 70(5)2,0(6)8(7)36 (8)1(9)3,1,-1,3,1,-1(10)a=12 ,y=12(11)i=6,k=4 (12)1,-2 4.程序填空(1)x:y , u:z(2)m=n , m!=0,m=m/10(3)teps , t*n/(2*n+1) , printf(“%lf\n”,2*s) (4)m%5==0 ,printf(“%d\n”,k) (5)cx=getchar() , cx!=front , cx(6)double s=0, 1.0/k , %lf (7)s=0 , sgmin, 5.编程题(1). #include stdio.h int main() {double x,y; scanf(%lf,x); if(x1) y=x;else if(x=1.0x10) y=2*x-11; elsey=3*x-11;printf(%lf\n,y); return 0; } (2).#include stdio.h int main() {double x,y,z,min;scanf(%lf%lf%lf,x,y,z); if(xy) min=y; else min=x; if(minz)min=z;printf(min=%lf\n,min); return 0; } (3).#include stdio.h int main() {int y,m,d,flag,s=0,w,i;scanf(%d%d%d,y,m,d);flag=(y%4==0y%100!=0||y%400==0);w=((y-1)*365+(y-1)/4-(y-1)/100+(y-1)/400)%7;for(i=1;i=m;i++) {switch(i) {case 1:s=d;break; case 2:s=31+d;break; case 3:s=59+d;break; case 4:s=90+d;break; case 5:s=120+d;break; case6:s=151+d;break; case 7:s=181+d;break; case8:s=212+d;break; case 9:s=243+d;break; case10:s=273+d;break; case 11:s=304+d;break; case12:s=334+d;break;} }s=(w+s)%7; if(s==0)printf(星期日\n); elseprintf(星期%d\n,s); return 0; }(4).#include stdio.h int main() {float p,r;scanf(%f,p); if(p=10) r=p*0.1;else if(p10p=20) r=10*0.1+(p-10)*0.075; else if(p20p=40)r=10*0.1+10*0.075+(p-20)*0.05; else if(p40p=60)r=10*0.1+10*0.075+20*0.05+(p-40)*0.03;else if(p60p=100)r=10*0.1+10*0.075+20*0.05+20*0.03+(p-60)*0.015; else if(p100)r=10*0.1+10*0.075+20*0.05+20*0.03+40*0.015+(p-100)*0.01; printf(%f\n,r); return 0; } (5).#include stdio.h int main() {char c;while((c=getchar())!=\n) {if(c=ac=z) c=c-32; putchar(c);}return 0; } (6).#includestdio.h int main() {int m,k=2;printf(输入一个正整数:\n); scanf(%d,m); while(km) if(m%k==0) {printf(%4d,k); m=m/k; } else k++;printf(%4d\n,m); return 0; } (7).#includestdio.h int main() {int a,n,s=0,p=0,i;scanf(%d %d,n,a); for(i=1;i=n;i++) {p=p*10+a; s=s+p; }printf(%d\n,s); return 0; } (8).#includestdio.h int main(){int i,j,k;for(i=1;i=9;i++) for(j=0;j=9;j++) for(k=0;k=9;k++)printf(%5d,100*i+10*j+k); return 0; }(9).#includestdio.h #includemath.h int main() {float a=-10,b=10,x,f1,f2,f; f1=(((2*a-4)*a+3)*a)-6; f2=(((2*b-4)*b+3)*b)-6; do {x=(a+b)/2;f=(((2*x-4)*x+3)*x)-6; if(f*f10) { b=x; f2=f; } else { a=x;f1=f; }}while(fabs(f)=1e-6); printf(%6.2f\n,x); return 0; }(10).#includestdio.h#includemath.h int main() {int n=2;double eps,t,s=0,x;scanf(%lf %lf,x,eps); t=x; s=t;while(fabs(t)=eps) {t=-t*(2*n-3)*x*x/(2*n-2); s=s+t/(2*n); n++; }printf(%d,%lf\n,n,s); return 0; }(11).#includestdio.h int main() {unsigned long s,t=0,p=1; scanf(%u,s); while(s!=0) {if((s%10)%2!=0) {t=t+(s%10)*p; p=p*10; }s=s/10; }printf(%u\n,t); return 0; }第4章习题参考答案1.单项选择题1-5 dddbd 6-10 badcd 11-14 bdab 2.填空题(1)2(2)嵌套,递归(3)全局变量,局部变量,静态变量,动态变量(4)auto , static , register , extern (5)外部变量(6)编译,运行 3.阅读程序,指出结果(1)15(2)5(3)5,4,3 (4)i=5 i=2 i=2 i=4 i=2(5)求水仙花数(6)-5*5*5(7)30 (8)0 10 1 11 2 124.程序填空(1)float fun(float , float) , x+y,x-y, z+y,z-y (2)x , x*x+1 (3)s=0 , a=a+b 5.编程题(1).while(s!=0) #includestdio.h { unsigned int fun(unsigned int);p=p+s%10; int main() s=s/10; { } unsigned int s; return p; scanf(%u,s); } printf(%u\n,fun(s)); (2). return 0;#includestdio.h } #includestdlib.h unsigned int fun(unsignedint s) #includemath.h { void f1(float,float,float,float); unsigned int p=0; void f2(float,float,float,float);【篇二:《c语言程序设计》课后习题答案(第四版)谭浩强】t>1.1什么是计算机程序11.2什么是计算机语言11.3c语言的发展及其特点31.4最简单的c语言程序51.4.1最简单的c语言程序举例61.4.2c语言程序的结构101.5运行c程序的步骤与方法121.6程序设计的任务141-5 #include stdio.hint main ( ){ printf (**************************\n\n);printf( very good!\n\n);printf (**************************\n);return 0;}1-6#include stdio.hint main(){int a,b,c,max;printf(please input a,b,c:\n);scanf(%d,%d,%d,a,b,c);max=a;if (maxb)max=b;if (maxc)max=c;printf(the largest number is %d\n,max);return 0;}第2章算法——程序的灵魂162.1什么是算法162.2简单的算法举例172.3算法的特性212.4怎样表示一个算法222.4.1用自然语言表示算法222.4.2用流程图表示算法222.4.3三种基本结构和改进的流程图262.4.4用n?s流程图表示算法282.4.5用伪代码表示算法312.4.6用计算机语言表示算法322.5结构化程序设计方法34习题36第章最简单的c程序设计——顺序程序设计37 3.1顺序程序设计举例373.2数据的表现形式及其运算393.2.1常量和变量393.2.2数据类型423.2.3整型数据443.2.4字符型数据473.2.5浮点型数据493.2.6怎样确定常量的类型513.2.7运算符和表达式523.3c语句573.3.1c语句的作用和分类573.3.2最基本的语句——赋值语句593.4数据的输入输出653.4.1输入输出举例653.4.2有关数据输入输出的概念673.4.3用printf函数输出数据683.4.4用scanf函数输入数据753.4.5字符数据的输入输出78习题823-1 #include stdio.h#include math.hint main(){float p,r,n;r=0.1;n=10;p=pow(1+r,n);printf(p=%f\n,p);return 0;}3-2-1#include stdio.h#include math.hint main(){float r5,r3,r2,r1,r0,p,p1,p2,p3,p4,p5;p=1000;r5=0.0585;r3=0.054;r2=0.0468;r1=0.0414;r0=0.0072;p1=p*((1+r5)*5);// 一次存5年期p2=p*(1+2*r2)*(1+3*r3); // 先存2年期,到期后将本息再存3年期 p3=p*(1+3*r3)*(1+2*r2); // 先存3年期,到期后将本息再存2年期p4=p*pow(1+r1,5); // 存1年期,到期后将本息存再存1年期,连续存5次 p5=p*pow(1+r0/4,4*5); // 存活期存款。

c 程序设计第二版课后习题答案

c  程序设计第二版课后习题答案

c 程序设计第二版课后习题答案C程序设计第二版课后习题答案C程序设计是计算机科学与技术专业中一门重要的课程,它涉及到了计算机程序设计的基本概念、语法和技巧。

而《C程序设计第二版》是一本经典的教材,它通过丰富的例子和习题,帮助学生巩固和扩展他们的编程知识。

在学习这门课程时,课后习题是非常重要的一部分。

通过解答习题,我们可以更好地理解和掌握所学的知识,并且提高我们的编程能力。

然而,有时候我们可能会遇到一些困难,无法找到正确的答案。

因此,本文将为大家提供一些C程序设计第二版课后习题的答案,希望能对大家的学习有所帮助。

1. 第一章习题第一章主要介绍了C语言的基本概念和语法。

在习题中,我们需要编写一些简单的程序来练习基本的输入输出操作。

以下是一些可能的答案:```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);printf("您输入的整数是:%d\n", num);return 0;}```2. 第二章习题第二章主要介绍了C语言的数据类型和运算符。

在习题中,我们需要编写一些程序来练习不同数据类型的使用和运算符的操作。

以下是一些可能的答案:```c#include <stdio.h>int main() {int a = 10;float b = 3.14;char c = 'A';printf("a + b = %f\n", a + b);printf("a * b = %f\n", a * b);printf("a / b = %f\n", a / b);printf("c + 1 = %c\n", c + 1);return 0;}```3. 第三章习题第三章主要介绍了C语言的控制结构,包括条件语句和循环语句。

c程序设计第二版完整答案

c程序设计第二版完整答案
而const定义则是象定义一个变量一样定义一个常量标识符系统要按照类型要求为该标识符分配内存单元同时在将常量放入单元时进行类型检查如果类型不匹配类型相容的会进行系统的类型转换不相容的则要提示错误
第一章C++基础知识习题
1.1判断下列标识符的合法性。
sin book5arry _name Example2.1 main
int array[5]={1,2,3,4,5}; char s[]="Hello";
答:"China"文字常量
constint n=10;常变量
int m=5;变量
'a'文字常量
char ch='a'变量
int array[5]={1,2,3,4,5};变量
char s[]="Hello";变量
1.4将下列算式或叙述用C++表达式描述。
}
result=1;
for(i=2;i<=n;i++){
jch*=i; //jch是i的阶乘,注意n!=n*(n-1)!这样可少一层循环
result+=jch;
}
cout<<result<<endl;
return 0;
}
2.8
#include <iostream>
using namespace std;
}
m-=3;
}
解答:注意continue语句的使用
初值
m=0
k=1
第1次循环后
m=5
k=2
第2次循环后
m=2
k=3
第3次循环后

C 程序设计教程第二版习题答案

C  程序设计教程第二版习题答案

C 程序设计教程第二版习题答案C 程序设计教程第二版习题答案C 程序设计是一门广泛应用于计算机科学和工程领域的编程语言,它具有高效、灵活和可移植等优点。

对于初学者来说,掌握C 程序设计的基本知识是非常重要的。

而《C 程序设计教程》是一本经典的教材,为学习者提供了一系列的习题来巩固所学知识。

本文将为大家提供《C 程序设计教程第二版》习题的答案,帮助大家更好地理解和掌握C 程序设计。

第一章:C 程序设计入门1.1 习题答案:1. 编写一个C程序,输出"Hello, World!"。

```c#include <stdio.h>int main() {printf("Hello, World!");return 0;}```1.2 习题答案:1. 编写一个C程序,输入两个整数,然后输出它们的和。

```c#include <stdio.h>int main() {int num1, num2, sum;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);sum = num1 + num2;printf("两个整数的和为:%d", sum);return 0;}```第二章:C 程序设计基本要素2.1 习题答案:1. 编写一个C程序,输入一个字符,然后输出它的ASCII码。

```c#include <stdio.h>int main() {char ch;printf("请输入一个字符:");scanf("%c", &ch);printf("该字符的ASCII码为:%d", ch);return 0;}```2.2 习题答案:1. 编写一个C程序,输入一个整数,然后输出它的绝对值。

c语言程序设计教程(第2版)完整编程答案1-8章

c语言程序设计教程(第2版)完整编程答案1-8章

9 c 32 ,程序中有多处错误, 5
请改正错误后运行正确的程序。 答:#include <stdio.h> #include <stdio.h> main() main() {float c=0,f=0; {float c=0,F=0; printf("input c:"); printf("input c:"); scanf("%f",&c); scanf("%f", c); f=((float)9/5)*c+32; f=(9/5)·c+32; printf("c=%f,f=%f\n",c,f); print("c=%f,f=%f\n",&c,&f); } } 扩展:把程序功能改为:输入华氏温度 f,计算摄氏温度 c。 #include <stdio.h> main()
0 x 2 2、编写程序,求下面分段函数的值,要求 x 的值从键盘输入。 y 2 x 3 10
(当x 0时) (当0 x 5时) (当5 x 10时) (当x 10时)
#include <stdio.h> main() { double x=0.0,y=0.0; int k=0; scanf("%lf",&x); k=1*(x<0)+2*(x>=0&&x<5)+3*(x>=5&&x<10)+4*(x>=10); switch(k) { case 1: y=0;break; case 2: y=x+2;break; case 3: y=x*x-3;break; case 4: y=10;break; } printf("x=%lf,y=%lf\n",x,y); } 训练 3.1:输入一个字符,如果是数字字符,则转换成对应的数字。 #include <stdio.h> main() { char ch='\0'; int a=-1; ch=getchar(); if(ch>='0'&&ch<='9') { a=ch-'0'; printf("charter %c ,digit:%d\n",ch,a); } else printf("%c is not digit\n",ch); } 扩展:将程序的功能改为:如果所输入的字符为大写字母,则将其转换为小写字母。请使用库函数判断和转 换。 #include <stdio.h> #include <ctype.h> main() { char ch='\0'; ch=getchar(); printf("the input charter is %c \n",ch); if(isupper(ch)) { ch=tolower(ch); printf("The corresponding lowercase letter is %c\n",ch); } else printf("It is not the capital letter!\n"); } 训练 3.2:求一元二次方程 ax2+bx+c=0 的实根(要求 a,b,c 的值从键盘输入,a≠0) #include <stdio.h> #include <math.h> main()

c 程序设计(第2版)课后习题答案

c 程序设计(第2版)课后习题答案

c 程序设计(第2版)课后习题答案C 程序设计(第2版)是一本经典的计算机编程教材,被广泛应用于计算机科学与技术专业的教学中。

该教材的每一章都附带了一系列的习题,这些习题在巩固学生对于 C 语言的理解和掌握方面起到了重要的作用。

然而,很多学生在自学或者课后复习的过程中常常会遇到习题解答的困扰。

因此,本文将为大家提供一些 C 程序设计(第2版)课后习题的答案,希望能够对大家的学习有所帮助。

第一章:C 程序设计概述1.1 习题解答:1) C 程序设计的特点包括高效性、可移植性、灵活性和可扩展性。

2) C 程序设计的基本结构包括预处理指令、函数定义和主函数。

3) C 程序设计的编译过程包括预处理、编译、汇编和链接四个阶段。

第二章:C 语言基础2.1 习题解答:1) C 语言中的标识符是指用于标识变量、函数、数组等各种程序实体的名称。

标识符的命名规则包括:只能由字母、数字和下划线组成,且不能以数字开头;不能使用 C 语言的关键字作为标识符;标识符区分大小写。

2) C 语言中的常量是指在程序中直接使用的固定值,包括整型常量、实型常量、字符常量和字符串常量。

3) C 语言中的变量是指用于存储数据的内存空间,包括整型变量、实型变量、字符变量和字符串变量。

第三章:运算符和表达式3.1 习题解答:1) C 语言中的算术运算符包括加法运算符(+)、减法运算符(-)、乘法运算符(*)、除法运算符(/)和取模运算符(%)等。

2) C 语言中的关系运算符包括大于运算符(>)、小于运算符(<)、等于运算符(==)、不等于运算符(!=)等。

3) C 语言中的逻辑运算符包括与运算符(&&)、或运算符(||)和非运算符(!)等。

第四章:选择结构4.1 习题解答:1) C 语言中的 if 语句用于实现单一条件的判断,格式为:if (条件表达式) {语句块}。

2) C 语言中的 if-else 语句用于实现两个条件的判断,格式为:if (条件表达式) {语句块1} else {语句块2}。

C语言程序设计:现代方法(第2版)第二章全部习题答案

C语言程序设计:现代方法(第2版)第二章全部习题答案

C语⾔程序设计:现代⽅法(第2版)第⼆章全部习题答案前⾔本⼈在通过《C语⾔程序设计:现代⽅法(第2版)》⾃学C语⾔时,发现国内并没有该书完整的课后习题答案,所以就想把⾃⼰在学习过程中所做出的答案分享出来,以供⼤家参考。

这些答案是本⼈⾃⼰解答,并参考GitHub上相关的分享和相关资料。

因为并没有权威的答案来源,所以可能会存在错误的地⽅,如有错误还希望⼤家能够帮助指出。

第⼆章练习题和编程题答案练习题2.2节1.建⽴并运⾏由Kernighan和Ritchie编写的著名的“hello world”程序:1 #include <stdio.h>2 int main(void)3 {4 printf("hello world!\n");5 }在编译时是否有警告信息?如果有,需要如何改进呢?答:如果使⽤部分⽐较⽼的编译器如turbo C等,会⽣成警告信息,指出main函数并没有返回任何值。

这是因为在声明main函数时使⽤了int,表明函数会返回⼀个整型数值,这个数值为任意(因为main后⾯是void)。

但是上⾯的代码中并没有return语句,所以并不会返回任何值。

加⼊return语句后便可消除警告。

1 /* 加⼊return语句后的版本 */2 #include <stdio.h>3 int main(void)4 {5 printf("Hello world!\n");6 return 0;7 }如果是使⽤IDE中的编译器,且IDE版本⽐较新(如本⼈⽬前使⽤的Code:Blocks)即使没有return语句,编译器也不会⽣成警告信息。

2.思考下⾯的程序:1 #include <stdio.h>2int main(void)3 {4 printf("Parkinson's Law:\nWork expands so as to ");5 printf("fill the time\n");6 printf("available for its completion.\n");7return0;8 }(a)请指出程序中的指令和语句。

c语言程序设计现代方法(第二版)习题答案

c语言程序设计现代方法(第二版)习题答案

Chapter 2Answers to Selected Exercises2. [was #2] (a) The program contains one directive (#include) and four statements (three calls of printf and one return).(b)Parkinson's Law:Work expands so as to fill the timeavailable for its completion.3. [was #4]#include <stdio.h>int main(void){int height = 8, length = 12, width = 10, volume;volume = height * length * width;printf("Dimensions: %dx%dx%d\n", length, width, height);printf("Volume (cubic inches): %d\n", volume);printf("Dimensional weight (pounds): %d\n", (volume + 165) / 166);return 0;}4. [was #6] Here's one possible program:#include <stdio.h>int main(void){int i, j, k;float x, y, z;printf("Value of i: %d\n", i);printf("Value of j: %d\n", j);printf("Value of k: %d\n", k);printf("Value of x: %g\n", x);printf("Value of y: %g\n", y);printf("Value of z: %g\n", z);return 0;}When compiled using GCC and then executed, this program produced the following output:Value of i: 5618848Value of j: 0Value of k: 6844404Value of x: 3.98979e-34Value of y: 9.59105e-39Value of z: 9.59105e-39The values printed depend on many factors, so the chance that you'll get exactly these numbers is small.5. [was #10] (a) is not legal because 100_bottles begins with a digit.8. [was #12] There are 14 tokens: a, =, (, 3, *, q, -, p, *, p, ), /, 3, and ;.Answers to Selected Programming Projects4. [was #8; modified]#include <stdio.h>int main(void){float original_amount, amount_with_tax;printf("Enter an amount: ");scanf("%f", &original_amount);amount_with_tax = original_amount * 1.05f;printf("With tax added: $%.2f\n", amount_with_tax);return 0;}The amount_with_tax variable is unnecessary. If we remove it, the program is slightly shorter:#include <stdio.h>int main(void){float original_amount;printf("Enter an amount: ");scanf("%f", &original_amount);printf("With tax added: $%.2f\n", original_amount * 1.05f);return 0;}Chapter 3Answers to Selected Exercises2. [was #2](a) printf("%-8.1e", x);(b) printf("%10.6e", x);(c) printf("%-8.3f", x);(d) printf("%6.0f", x);5.[was #8] The values of x, i, and y will be 12.3, 45, and .6, respectively. Answers to Selected Programming Projects1. [was #4; modified]#include <stdio.h>int main(void){int month, day, year;printf("Enter a date (mm/dd/yyyy): ");scanf("%d/%d/%d", &month, &day, &year);printf("You entered the date %d%.2d%.2d\n", year, month, day);return 0;}3. [was #6; modified]#include <stdio.h>int main(void){int prefix, group, publisher, item, check_digit;printf("Enter ISBN: ");scanf("%d-%d-%d-%d-%d", &prefix, &group, &publisher, &item,&check_digit);printf("GS1 prefix: %d\n", prefix);printf("Group identifier: %d\n", group);printf("Publisher code: %d\n", publisher);printf("Item number: %d\n", item);printf("Check digit: %d\n", check_digit);/* The five printf calls can be combined as follows:printf("GS1 prefix: %d\nGroup identifier: %d\nPublishercode: %d\nItem number: %d\nCheck digit: %d\n",prefix, group, publisher, item, check_digit);*/return 0;}Chapter 4Answers to Selected Exercises2.[was #2] Not in C89. Suppose that i is 9 and j is 7. The value of (-i)/j could be either –1 or –2, depending on the implementation. On the other hand, the value of -(i/j) is always –1, regardless of the implementation. In C99, on the other hand, the value of (-i)/j must be equal to the value of -(i/j).9. [was #6](a) 63 8(b) 3 2 1(c) 2 -1 3(d) 0 0 013. [was #8] The expression ++i is equivalent to (i += 1). The value of both expressions is i after the increment has been performed.Answers to Selected Programming Projects2. [was #4]#include <stdio.h>int main(void){int n;printf("Enter a three-digit number: ");scanf("%d", &n);printf("The reversal is: %d%d%d\n", n % 10, (n / 10) % 10, n / 100);return 0;}Chapter 5Answers to Selected Exercises2. [was #2](a) 1(b) 1(c) 1(d) 14. [was #4] (i > j) - (i < j)6. [was #12] Yes, the statement is legal. When n is equal to 5, it does nothing, since 5 is not equal to –9.10. [was #16] The output isonetwosince there are no break statements after the cases.Answers to Selected Programming Projects2. [was #6]#include <stdio.h>int main(void){int hours, minutes;printf("Enter a 24-hour time: ");scanf("%d:%d", &hours, &minutes);printf("Equivalent 12-hour time: ");if (hours == 0)printf("12:%.2d AM\n", minutes);else if (hours < 12)printf("%d:%.2d AM\n", hours, minutes);else if (hours == 12)printf("%d:%.2d PM\n", hours, minutes);elseprintf("%d:%.2d PM\n", hours - 12, minutes);return 0;}4. [was #8; modified]#include <stdio.h>int main(void){int speed;printf("Enter a wind speed in knots: ");scanf("%d", &speed);if (speed < 1)printf("Calm\n");else if (speed <= 3)printf("Light air\n");else if (speed <= 27)printf("Breeze\n");else if (speed <= 47)printf("Gale\n");else if (speed <= 63)printf("Storm\n");elseprintf("Hurricane\n");return 0;}6. [was #10]#include <stdio.h>int main(void){int check_digit, d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total;printf("Enter the first (single) digit: ");scanf("%1d", &d);printf("Enter first group of five digits: ");scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5);printf("Enter second group of five digits: ");scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5);printf("Enter the last (single) digit: ");scanf("%1d", &check_digit);first_sum = d + i2 + i4 + j1 + j3 + j5;second_sum = i1 + i3 + i5 + j2 + j4;total = 3 * first_sum + second_sum;if (check_digit == 9 - ((total - 1) % 10))printf("VALID\n");elseprintf("NOT VALID\n");return 0;}10. [was #14]#include <stdio.h>int main(void){int grade;printf("Enter numerical grade: ");scanf("%d", &grade);if (grade < 0 || grade > 100) {printf("Illegal grade\n");return 0;}switch (grade / 10) {case 10:case 9: printf("Letter grade: A\n");break;case 8: printf("Letter grade: B\n");break;case 7: printf("Letter grade: C\n");break;case 6: printf("Letter grade: D\n");break;case 5:case 4:case 3:case 2:case 1:case 0: printf("Letter grade: F\n");break;}return 0;}Chapter 6Answers to Selected Exercises4.[was #10] (c) is not equivalent to (a) and (b), because i is incremented before the loop body is executed.10. [was #12] Consider the following while loop:while (…) {…continue;…}The equivalent code using goto would have the following appearance:while (…) {…goto loop_end;…loop_end: ; /* null statement */}12. [was #14]for (d = 2; d * d <= n; d++)if (n % d == 0)break;The if statement that follows the loop will need to be modified as well:if (d * d <= n)printf("%d is divisible by %d\n", n, d);elseprintf("%d is prime\n", n);14. [was #16] The problem is the semicolon at the end of the first line. If we remove it, the statement is now correct:if (n % 2 == 0)printf("n is even\n");Answers to Selected Programming Projects2. [was #2]#include <stdio.h>int main(void){int m, n, remainder;printf("Enter two integers: ");scanf("%d%d", &m, &n);while (n != 0) {remainder = m % n;m = n;n = remainder;}printf("Greatest common divisor: %d\n", m);return 0;}4. [was #4]#include <stdio.h>int main(void){float commission, value;printf("Enter value of trade: ");scanf("%f", &value);while (value != 0.0f) {if (value < 2500.00f)commission = 30.00f + .017f * value;else if (value < 6250.00f)commission = 56.00f + .0066f * value;else if (value < 20000.00f)commission = 76.00f + .0034f * value;else if (value < 50000.00f)commission = 100.00f + .0022f * value;else if (value < 500000.00f)commission = 155.00f + .0011f * value;elsecommission = 255.00f + .0009f * value;if (commission < 39.00f)commission = 39.00f;printf("Commission: $%.2f\n\n", commission);printf("Enter value of trade: ");scanf("%f", &value);}return 0;}6. [was #6]#include <stdio.h>int main(void){int i, n;printf("Enter limit on maximum square: ");scanf("%d", &n);for (i = 2; i * i <= n; i += 2)printf("%d\n", i * i);return 0;}8. [was #8]#include <stdio.h>int main(void){int i, n, start_day;printf("Enter number of days in month: ");scanf("%d", &n);printf("Enter starting day of the week (1=Sun, 7=Sat): "); scanf("%d", &start_day);/* print any leading "blank dates" */for (i = 1; i < start_day; i++)printf(" ");/* now print the calendar */for (i = 1; i <= n; i++) {printf("%3d", i);if ((start_day + i - 1) % 7 == 0)printf("\n");}return 0;}Chapter 7Answers to Selected Exercises3. [was #4] (b) is not legal.4.[was #6] (d) is illegal, since printf requires a string, not a character, as its first argument.10.[was #14] unsigned int, because the (int) cast applies only to j, not j * k.12. [was #16] The value of i is converted to float and added to f, then the result is converted to double and stored in d.14. [was #18] No. Converting f to int will fail if the value stored inf exceeds the largest value of type int.Answers to Selected Programming Projects1.[was #2] short int values are usually stored in 16 bits, causing failure at 182. int and long int values are usually stored in 32 bits, with failure occurring at 46341.2. [was #8]#include <stdio.h>int main(void){int i, n;char ch;printf("This program prints a table of squares.\n");printf("Enter number of entries in table: ");scanf("%d", &n);ch = getchar();/* dispose of new-line character following number of entries *//* could simply be getchar(); */for (i = 1; i <= n; i++) {printf("%10d%10d\n", i, i * i);if (i % 24 == 0) {printf("Press Enter to continue...");ch = getchar(); /* or simply getchar(); */}}return 0;}5. [was #10]#include <ctype.h>#include <stdio.h>int main(void){int sum = 0;char ch;printf("Enter a word: ");while ((ch = getchar()) != '\n')switch (toupper(ch)) {case 'D': case 'G':sum += 2; break;case 'B': case 'C': case 'M': case 'P':sum += 3; break;case 'F': case 'H': case 'V': case 'W': case 'Y': sum += 4; break;case 'K':sum += 5; break;case 'J': case 'X':sum += 8; break;case 'Q': case 'Z':sum += 10; break;default:sum++; break;}printf("Scrabble value: %d\n", sum);return 0;}6. [was #12]#include <stdio.h>int main(void){printf("Size of int: %d\n", (int) sizeof(int));printf("Size of short: %d\n", (int) sizeof(short));printf("Size of long: %d\n", (int) sizeof(long));printf("Size of float: %d\n", (int) sizeof(float));printf("Size of double: %d\n", (int) sizeof(double));printf("Size of long double: %d\n", (int) sizeof(long double));return 0;}Since the type of a sizeof expression may vary from one implementation to another, it's necessary in C89 to cast sizeof expressions to a known type before printing them. The sizes of the basic types are small numbers, so it's safe to cast them to int. (In general, however, it's best to cast sizeof expressions to unsigned long and print them using %lu.) In C99, we can avoid the cast by using the %zu conversion specification.Chapter 8Answers to Selected Exercises1.[was #4] The problem with sizeof(a) / sizeof(t) is that it can't easily be checked for correctness by someone reading the program. (The reader would have to locate the declaration of a and make sure that its elements have type t.)2. [was #8] To use a digit d (in character form) as a subscript into the array a, we would write a[d-'0']. This assumes that digits have consecutive codes in the underlying character set, which is true of ASCII and other popular character sets.7. [was #10]const int segments[10][7] = {{1, 1, 1, 1, 1, 1},{0, 1, 1},{1, 1, 0, 1, 1, 0, 1},{1, 1, 1, 1, 0, 0, 1},{0, 1, 1, 0, 0, 1, 1},{1, 0, 1, 1, 0, 1, 1},{1, 0, 1, 1, 1, 1, 1},{1, 1, 1},{1, 1, 1, 1, 1, 1, 1},{1, 1, 1, 1, 0, 1, 1}};Answers to Selected Programming Projects2. [was #2]#include <stdio.h>int main(void){int digit_count[10] = {0};int digit;long n;printf("Enter a number: ");scanf("%ld", &n);while (n > 0) {digit = n % 10;digit_count[digit]++;n /= 10;}printf ("Digit: ");for (digit = 0; digit <= 9; digit++)printf("%3d", digit);printf("\nOccurrences:");for (digit = 0; digit <= 9; digit++)printf("%3d", digit_count[digit]);printf("\n");return 0;}5. [was #6]#include <stdio.h>#define NUM_RATES ((int) (sizeof(value) / sizeof(value[0]))) #define INITIAL_BALANCE 100.00int main(void){int i, low_rate, month, num_years, year;double value[5];printf("Enter interest rate: ");scanf("%d", &low_rate);printf("Enter number of years: ");scanf("%d", &num_years);printf("\nYears");for (i = 0; i < NUM_RATES; i++) {printf("%6d%%", low_rate + i);value[i] = INITIAL_BALANCE;}printf("\n");for (year = 1; year <= num_years; year++) {printf("%3d ", year);for (i = 0; i < NUM_RATES; i++) {for (month = 1; month <= 12; month++)value[i] += ((double) (low_rate + i) / 12) / 100.0 * value[i]; printf("%7.2f", value[i]);}printf("\n");}return 0;}8. [was #12]#include <stdio.h>#define NUM_QUIZZES 5#define NUM_STUDENTS 5int main(void){int grades[NUM_STUDENTS][NUM_QUIZZES];int high, low, quiz, student, total;for (student = 0; student < NUM_STUDENTS; student++) {printf("Enter grades for student %d: ", student + 1);for (quiz = 0; quiz < NUM_QUIZZES; quiz++)scanf("%d", &grades[student][quiz]);}printf("\nStudent Total Average\n");for (student = 0; student < NUM_STUDENTS; student++) {printf("%4d ", student + 1);total = 0;for (quiz = 0; quiz < NUM_QUIZZES; quiz++)total += grades[student][quiz];printf("%3d %3d\n", total, total / NUM_QUIZZES);}printf("\nQuiz Average High Low\n");for (quiz = 0; quiz < NUM_QUIZZES; quiz++) {printf("%3d ", quiz + 1);total = 0;high = 0;low = 100;for (student = 0; student < NUM_STUDENTS; student++) {total += grades[student][quiz];if (grades[student][quiz] > high)high = grades[student][quiz];if (grades[student][quiz] < low)low = grades[student][quiz];}printf("%3d %3d %3d\n", total / NUM_STUDENTS, high, low); }return 0;}Chapter 9Answers to Selected Exercises2. [was #2]int check(int x, int y, int n){return (x >= 0 && x <= n - 1 && y >= 0 && y <= n - 1);}4. [was #4]int day_of_year(int month, int day, int year){int num_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int day_count = 0, i;for (i = 1; i < month; i++)day_count += num_days[i-1];/* adjust for leap years, assuming they are divisible by 4 */if (year % 4 == 0 && month > 2)day_count++;return day_count + day;}Using the expression year % 4 == 0 to test for leap years is not completely correct. Centuries are special cases: if a year is a multiple of 100, then it must also be a multiple of 400 in order to be a leap year. The correct test isyear % 4 == 0 && (year % 100 != 0 || year % 400 == 0)6. [was #6; modified]int digit(int n, int k){int i;for (i = 1; i < k; i++)n /= 10;return n % 10;}8. [was #8] (a) and (b) are valid prototypes. (c) is illegal, since it doesn't specify the type of the parameter. (d) incorrectly specifies that f returns an int value in C89; in C99, omitting the return type is illegal.10. [was #10](a)int largest(int a[], int n){int i, max = a[0];for (i = 1; i < n; i++)if (a[i] > max)max = a[i];return max;}(b)int average(int a[], int n){int i, avg = 0;for (i = 0; i < n; i++)avg += a[i];return avg / n;}(c)int num_positive(int a[], int n){int i, count = 0;for (i = 0; i < n; i++)if (a[i] > 0)count++;return count;}15. [was #12; modified]double median(double x, double y, double z) {double result;if (x <= y)if (y <= z) result = y;else if (x <= z) result = z;else result = x;else {if (z <= y) result = y;else if (x <= z) result = x;else result = z;}return result;}17. [was #14]int fact(int n){int i, result = 1;for (i = 2; i <= n; i++)result *= i;return result;}19. [was #16] The following program tests the pb function:#include <stdio.h>void pb(int n);int main(void){int n;printf("Enter a number: ");scanf("%d", &n);printf("Output of pb: ");pb(n);printf("\n");return 0;}void pb(int n){if (n != 0) {pb(n / 2);putchar('0' + n % 2);}}pb prints the binary representation of the argument n, assuming that n is greater than 0. (We also assume that digits have consecutive codes in the underlying character set.) For example:Enter a number: 53Output of pb: 110101A trace of pb's execution would look like this:pb(53) finds that 53 is not equal to 0, so it callspb(26), which finds that 26 is not equal to 0, so it calls pb(13), which finds that 13 is not equal to 0, so it calls pb(6), which finds that 6 is not equal to 0, so it callspb(3), which finds that 3 is not equal to 0, so it callspb(1), which finds that 1 is not equal to 0, so it callspb(0), which finds that 0 is equal to 0, so it returns, causingpb(1) to print 1 and return, causingpb(3) to print 1 and return, causingpb(6) to print 0 and return, causingpb(13) to print 1 and return, causingpb(26) to print 0 and return, causingpb(53) to print 1 and return.Chapter 10Answers to Selected Exercises1. [was #2] (a) a, b, and c are visible.(b) a, and d are visible.(c) a, d, and e are visible.(d) a and f are visible.Answers to Selected Programming Projects3. [was #4]#include <stdbool.h> /* C99 only */#include <stdio.h>#include <stdlib.h>#define NUM_CARDS 5#define RANK 0#define SUIT 1/* external variables */int hand[NUM_CARDS][2];/* 0 1____ ____0 |____|____|1 |____|____|2 |____|____|3 |____|____|4 |____|____|rank suit*/bool straight, flush, four, three;int pairs; /* can be 0, 1, or 2 *//* prototypes */void read_cards(void);void analyze_hand(void);void print_result(void);/********************************************************** * main: Calls read_cards, analyze_hand, and print_result * * repeatedly. * **********************************************************/ int main(void){for (;;) {read_cards();analyze_hand();print_result();}}/********************************************************** * read_cards: Reads the cards into the external variable * * hand; checks for bad cards and duplicate * * cards. * **********************************************************/ void read_cards(void){char ch, rank_ch, suit_ch;int i, rank, suit;bool bad_card, duplicate_card;int cards_read = 0;while (cards_read < NUM_CARDS) {bad_card = false;printf("Enter a card: ");rank_ch = getchar();switch (rank_ch) {case '0': exit(EXIT_SUCCESS);case '2': rank = 0; break;case '3': rank = 1; break;case '4': rank = 2; break;case '5': rank = 3; break;case '6': rank = 4; break;case '7': rank = 5; break;case '8': rank = 6; break;case '9': rank = 7; break;case 't': case 'T': rank = 8; break;case 'j': case 'J': rank = 9; break;case 'q': case 'Q': rank = 10; break;case 'k': case 'K': rank = 11; break;case 'a': case 'A': rank = 12; break;default: bad_card = true;}suit_ch = getchar();switch (suit_ch) {case 'c': case 'C': suit = 0; break;case 'd': case 'D': suit = 1; break;case 'h': case 'H': suit = 2; break;case 's': case 'S': suit = 3; break;default: bad_card = true;}while ((ch = getchar()) != '\n')if (ch != ' ') bad_card = true;if (bad_card) {printf("Bad card; ignored.\n");continue;}duplicate_card = false;for (i = 0; i < cards_read; i++)if (hand[i][RANK] == rank && hand[i][SUIT] == suit) { printf("Duplicate card; ignored.\n");duplicate_card = true;break;}if (!duplicate_card) {hand[cards_read][RANK] = rank;hand[cards_read][SUIT] = suit;cards_read++;}}}/********************************************************** * analyze_hand: Determines whether the hand contains a * * straight, a flush, four-of-a-kind, * * and/or three-of-a-kind; determines the * * number of pairs; stores the results into * * the external variables straight, flush, * * four, three, and pairs. * **********************************************************/ void analyze_hand(void){int rank, suit, card, pass, run;straight = true;flush = true;four = false;three = false;pairs = 0;/* sort cards by rank */for (pass = 1; pass < NUM_CARDS; pass++)for (card = 0; card < NUM_CARDS - pass; card++) {rank = hand[card][RANK];suit = hand[card][SUIT];if (hand[card+1][RANK] < rank) {hand[card][RANK] = hand[card+1][RANK];hand[card][SUIT] = hand[card+1][SUIT];hand[card+1][RANK] = rank;hand[card+1][SUIT] = suit;}}/* check for flush */suit = hand[0][SUIT];for (card = 1; card < NUM_CARDS; card++)if (hand[card][SUIT] != suit)flush = false;/* check for straight */for (card = 0; card < NUM_CARDS - 1; card++)if (hand[card][RANK] + 1 != hand[card+1][RANK])straight = false;/* check for 4-of-a-kind, 3-of-a-kind, and pairs bylooking for "runs" of cards with identical ranks */card = 0;while (card < NUM_CARDS) {rank = hand[card][RANK];run = 0;do {run++;card++;} while (card < NUM_CARDS && hand[card][RANK] == rank); switch (run) {case 2: pairs++; break;case 3: three = true; break;case 4: four = true; break;}}}/********************************************************** * print_result: Prints the classification of the hand, * * based on the values of the external * * variables straight, flush, four, three, * * and pairs. * **********************************************************/ void print_result(void){if (straight && flush) printf("Straight flush");else if (four) printf("Four of a kind");else if (three &&pairs == 1) printf("Full house");else if (flush) printf("Flush");else if (straight) printf("Straight");else if (three) printf("Three of a kind");else if (pairs == 2) printf("Two pairs");else if (pairs == 1) printf("Pair");else printf("High card");printf("\n\n");}5. [was #6]#include <stdbool.h> /* C99 only */#include <stdio.h>#include <stdlib.h>#define NUM_RANKS 13#define NUM_SUITS 4#define NUM_CARDS 5/* external variables */int num_in_rank[NUM_RANKS];int num_in_suit[NUM_SUITS];bool straight, flush, four, three;int pairs; /* can be 0, 1, or 2 *//* prototypes */void read_cards(void);void analyze_hand(void);void print_result(void);/********************************************************** * main: Calls read_cards, analyze_hand, and print_result * * repeatedly. * **********************************************************/ int main(void){for (;;) {read_cards();analyze_hand();print_result();}}/********************************************************** * read_cards: Reads the cards into the external * * variables num_in_rank and num_in_suit; * * checks for bad cards and duplicate cards. * **********************************************************/void read_cards(void){bool card_exists[NUM_RANKS][NUM_SUITS];char ch, rank_ch, suit_ch;int rank, suit;bool bad_card;int cards_read = 0;for (rank = 0; rank < NUM_RANKS; rank++) { num_in_rank[rank] = 0;for (suit = 0; suit < NUM_SUITS; suit++) card_exists[rank][suit] = false;}for (suit = 0; suit < NUM_SUITS; suit++)num_in_suit[suit] = 0;while (cards_read < NUM_CARDS) {bad_card = false;printf("Enter a card: ");rank_ch = getchar();switch (rank_ch) {case '0': exit(EXIT_SUCCESS); case '2': rank = 0; break;case '3': rank = 1; break;case '4': rank = 2; break;case '5': rank = 3; break;case '6': rank = 4; break;case '7': rank = 5; break;case '8': rank = 6; break;case '9': rank = 7; break;case 't': case 'T': rank = 8; break;case 'j': case 'J': rank = 9; break;case 'q': case 'Q': rank = 10; break; case 'k': case 'K': rank = 11; break; case 'a': case 'A': rank = 12; break; default: bad_card = true;}suit_ch = getchar();switch (suit_ch) {case 'c': case 'C': suit = 0; break;。

c程序设计第二版习题答案

c程序设计第二版习题答案

c程序设计第二版习题答案C程序设计第二版习题答案第一章:C语言概述1. 描述C语言的特点。

- C语言是一种结构化编程语言,以其高效性、灵活性和可移植性而闻名。

它支持过程式编程和低级内存操作,适合编写系统软件、操作系统和嵌入式系统。

2. 解释C语言的编译过程。

- C语言的编译过程通常包括预处理、编译、汇编和链接四个步骤。

预处理阶段处理宏定义和条件编译指令,编译阶段将源代码转换为汇编代码,汇编阶段将汇编代码转换为目标代码,链接阶段将目标代码与库函数链接生成可执行文件。

第二章:数据类型、运算符和表达式1. 列举C语言的基本数据类型。

- C语言的基本数据类型包括整型(int)、字符型(char)、浮点型(float和double)以及枚举型(enum)。

2. 说明赋值运算符的用法。

- 赋值运算符(=)用于将一个值赋给一个变量。

例如,`a = 5;`表示将整数5赋给变量a。

第三章:控制语句1. 描述if语句的语法结构。

- if语句的基本语法是:`if (条件) { 语句; }`。

如果条件为真,则执行花括号内的语句。

2. 解释while循环的工作原理。

- while循环在每次迭代之前都会检查条件是否为真。

如果条件为真,循环体内的语句将被执行,然后再次检查条件。

这个过程会一直重复,直到条件为假。

第四章:函数1. 函数的定义和声明。

- 函数定义是创建函数的主体,包括函数名、参数列表和函数体。

函数声明是告诉编译器函数的原型,包括函数名、返回类型和参数列表。

2. 函数的调用过程。

- 函数调用包括函数名和参数列表。

调用时,实际参数的值将传递给形式参数,函数执行完毕后,返回值(如果有的话)将返回给调用者。

第五章:数组和指针1. 数组的基本概念。

- 数组是一种数据结构,可以存储固定大小的同类型元素的集合。

数组的元素可以通过索引访问。

2. 指针的用途。

- 指针用于存储内存地址,可以直接操作内存。

指针可以指向基本数据类型、数组、结构体等。

C语言程序设计实例教程第2版习题答案作者李红第2章C语言基础知识.doc

C语言程序设计实例教程第2版习题答案作者李红第2章C语言基础知识.doc
main()
(B) a11b (C)
(D
D
a&&b (D)!(a=0)&&
(b!二0)
(D)0
(B
)o
int x=0245;
printf("%d",・・x);
getch()
}
(A) 244(B) 164(C) 245(D) 247
20.执行下列程序段吋输出结果是(D)。
#include <stdio.h>
(D) d=9+e++=d+9
A )o
(B) (x>=y) and (y>=z)
(D) (x>=y)&(y>=z)
11.在C语言中,若定义x和y为double类型,则表达式x=l,y=x+3/2的值是(C)。
(A)1(B)2(C) 2.0(D) 2.5
12.设a=12,则表达式a+=a-=a*=a的值是(C)。
main()
{
int x=6,y;
y=2+(x+=x++,x+8,++x);
printf(“%d〃,y);
getch();
}
(A) 13(B) 14(C) 15(D) 16
二.填空题
1.C语言的基本数据类型分为(
2.C语言的标识符只能由( 组成,而且第一个字符必须为(
3.C语言中,用关键字(int精度实型变量,用关键字(char
11.设
1x和y中有一个小于z(
2y是偶数(y%2=0
-2
1
b%4*(int)(x + y)%3/5的值为(

c程序设计谭浩强第二版答案

c程序设计谭浩强第二版答案

c程序设计谭浩强第二版答案谭浩强教授的《C程序设计》第二版是一本广泛使用的C语言教材,它以通俗易懂的语言和丰富的实例,帮助读者学习C语言的基础知识和编程技巧。

这本书的习题答案对于学习者来说是一个重要的参考资源。

以下是部分习题的答案,但请注意,这里仅提供部分答案,并不是全书的答案。

第一章 C语言概述1. 问题1:C语言的主要特点是什么?- 答案:C语言的主要特点包括简洁高效、结构化、可移植性、丰富的运算符、数据类型丰富、具有高级语言的优点和低级语言的特性。

2. 问题2:C语言适用于哪些领域?- 答案:C语言适用于系统软件开发、嵌入式系统开发、操作系统开发、高性能计算等领域。

第二章数据类型、运算符和表达式1. 问题1:C语言中的基本数据类型有哪些?- 答案:C语言中的基本数据类型包括整型(int)、字符型(char)、浮点型(float和double)。

2. 问题3:C语言中的算术运算符有哪些?- 答案:C语言中的算术运算符包括加(+)、减(-)、乘(*)、除(/)和模运算(%)。

第三章控制语句1. 问题1:C语言中的条件语句有哪几种?- 答案:C语言中的条件语句包括if语句、if...else语句和嵌套的if...else语句。

2. 问题2:while循环和do...while循环有什么区别?- 答案:while循环先判断条件再执行循环体,可能一次都不执行循环体;do...while循环至少执行一次循环体,然后再判断条件。

第四章函数1. 问题1:函数的定义和声明有什么区别?- 答案:函数的定义包括函数名、返回类型、参数列表和函数体;函数的声明只包括函数名、返回类型和参数列表。

2. 问题3:什么是递归函数?- 答案:递归函数是指在函数内部调用自身的函数。

第五章指针1. 问题1:什么是指针?- 答案:指针是一种变量,它存储了另一个变量的内存地址。

2. 问题2:指针和数组有什么联系?- 答案:数组名可以作为指针使用,指向数组的第一个元素的地址。

谭浩强c语言程序设计第二版答案

谭浩强c语言程序设计第二版答案

谭浩强c语言程序设计第二版答案谭浩强教授的《C语言程序设计》第二版是一本广受好评的C语言教材,它不仅详细介绍了C语言的基础知识,还通过大量的实例和习题来帮助读者加深理解。

以下是对该书中一些习题的答案解析,但请注意,这些答案仅供参考,实际编程时还需要根据具体问题进行调整。

第一章:C语言概述1. 问题1:为什么C语言既具有高级语言的特点,又具有低级语言的特点?- 答案:C语言具有高级语言的特点,因为它提供了丰富的数据类型、结构化编程和抽象能力。

同时,它又具有低级语言的特点,因为它允许直接访问内存地址,进行位操作,并且具有高效的运行速度。

第二章:数据类型、运算符与表达式1. 问题1:如何理解C语言中的变量?- 答案:变量是程序中存储数据的容器,它们具有特定的数据类型,用来存储整型、浮点型、字符型等数据。

变量在使用前需要声明,声明时需要指定变量的类型和名称。

2. 问题2:C语言中的运算符有哪些?- 答案:C语言中的运算符包括算术运算符(如+、-、*、/、%)、关系运算符(如<、>、==、!=)、逻辑运算符(如&&、||、!)、位运算符(如&、|、^、~、<<、>>)等。

第三章:控制结构1. 问题1:请解释if-else语句的工作原理。

- 答案:if-else语句是一种条件控制结构,它根据条件表达式的真假来决定执行哪一段代码。

如果条件表达式为真,则执行if语句块中的代码;如果为假,则执行else语句块中的代码。

2. 问题2:while循环和do-while循环有什么区别?- 答案:while循环先判断条件再执行循环体,如果条件为假,则不执行循环体。

do-while循环则先执行一次循环体,然后再判断条件,即使条件为假,循环体也会至少执行一次。

第四章:函数1. 问题1:函数的作用是什么?- 答案:函数是一段具有特定功能的代码块,可以被重复调用。

函数的使用可以提高代码的复用性,降低程序的复杂度,并且使程序结构更加清晰。

C程序设计语言 (第二版) 课后答案第二章

C程序设计语言 (第二版) 课后答案第二章

Exercise 2-1Write a program to determine the ranges of char , short , int , and long variables, both signed and unsigned , by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types.#include <stdio.h>#include <limits.h>intmain (){printf("Size of Char %d\n", CHAR_BIT);printf("Size of Char Max %d\n", CHAR_MAX);printf("Size of Char Min %d\n", CHAR_MIN);printf("Size of int min %d\n", INT_MIN);printf("Size of int max %d\n", INT_MAX);printf("Size of long min %ld\n", LONG_MIN);printf("Size of long max %ld\n", LONG_MAX);printf("Size of short min %d\n", SHRT_MIN);printf("Size of short max %d\n", SHRT_MAX);printf("Size of unsigned char %u\n", UCHAR_MAX);printf("Size of unsigned long %lu\n", ULONG_MAX);printf("Size of unsigned int %u\n", UINT_MAX);printf("Size of unsigned short %u\n", USHRT_MAX);return 0;}Exercise 2-2Write a loop equivalent to the for loop above without using && or || .#include <stdio.h>#define lim 100void main(){int i=0, c;char s[lim];while(i<lim-1){c=getchar();if(c='\n')break;if(c= EOF)break;++i;s[i]=c;}}Exercise 2-3Write the function htoi(s) , which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F .#define YES 1#define NO 0int htoi(s[]){int a ,I ,b ,n ;if(s[i]=='0'){++i;if(s[i]=='x'||s[i]=='X'){++i;}}n=0;b=YES;if( ;b==YES;++i){if(s[i]>='0'&&s[i]<='9')a=s[i]-'0';else if(s[i]>='a'&&s[i]<='z')a=s[i]-'a'+10;else if(s[i]>='A'&&s[i]<='Z')a=s[i]-'A'+10;elseb=NO;if (b==YES)n=16*n+a;}return n;}Exercise 2-4Write an alternate version of squeeze(s1,s2) that deletes each character in the string s1 that matches any character in the string s2 . void squeeze2(char s1[], char s2[]){int i, j, k;int instr2 = 0;for(i = j = 0; s1[i] != '\0'; i++){instr2 = 0;for(k = 0; s2[k] != '\0' && !instr2; k++){if(s2[k] == s1[i]){instr2 = 1;}}if(!instr2){s1[j++] = s1[i];}}s1[j] = '\0';}Exercise 2-5Write the function any(s1,s2) , which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2 . (The standard library function strpbrk does the same job but returns a pointer to the location.) int any(char s1[], char s2[]){int i;int j;int pos;pos = -1;for(i = 0; pos == -1 && s1[i] != '\0'; i++){for(j = 0; pos == -1 && s2[j] != '\0'; j++){if(s2[j] == s1[i]){pos = i;}}}return pos;Exercise 2-6Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.#include <stdio.h>unsigned setbits(unsigned x, int p, int n, unsigned y){return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));}int main(void){unsigned i;unsigned j;unsigned k;int p;int n;for(i = 0; i < 30000; i += 511){for(j = 0; j < 1000; j += 37){for(p = 0; p < 16; p++){for(n = 1; n <= p + 1; n++){k = setbits(i, p, n, j);printf("setbits(%u, %d, %d, %u) = %u\n", i, p, n, j, k);}}}}return 0;}Exercise 2-7Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.#include <stdio.h>int main(void){unsigned x;int p, n;for(x = 0; x < 700; x += 49)for(n = 1; n < 8; n++)for(p = 1; p < 8; p++)printf("%u, %d, %d: %u\n", x, n, p, invert(x, n, p));return 0;}Exercise 2-8Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions.#include <stdio.h>int main(void){unsigned x;int n;for(x = 0; x < 700; x += 49)for(n = 1; n < 8; n++)printf("%u, %d: %u\n", x, n, rightrot(x, n));return 0;}Exercise 2-9In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x . Explain why. Use this observation to write a faster version of bitcount .int bitcount(unsigned x){int b;for (b = 0; x != 0; x >>= 1)if (x & 01)b++;return b;}Exercise 2-10Rewrite the function lower, which converts upper case letters to lower case, with a conditional expression instead of if-else .#include <stdio.h>#include <string.h>#define TEST#define ORIGINAL 0#define SOLUTION 1#define PORTABLE_SOLUTION 0#if ORIGINALint lower(int c){if(c >= 'A' && c <= 'Z')return c + 'a' - 'A'; elsereturn c;}#endif。

c程序设计(第2版)课后习题答案

c程序设计(第2版)课后习题答案

c程序设计(第2版)课后习题答案C程序设计是一门基础的计算机编程课程,它教授学生如何使用C语言编写程序。

C语言是一种结构化编程语言,广泛用于系统软件、嵌入式系统和各种应用程序的开发。

以下是一些C程序设计课后习题的答案示例,这些答案仅供参考,具体习题的答案可能会有所不同。

第一章:C语言概述1. 简述C语言的特点。

- C语言是一种高级语言,同时具有汇编语言的效率。

- 它支持结构化编程,允许模块化设计。

- C语言具有丰富的运算符和数据类型。

- 它提供了指针功能,增强了编程的灵活性。

2. 描述C程序的基本结构。

- C程序由预处理指令、函数定义和主函数`main()`组成。

- 每个函数由函数声明、函数体和花括号包围的代码块组成。

第二章:数据类型、运算符和表达式1. 列出C语言的基本数据类型。

- 整型:`int`、`short int`、`long int`- 浮点型:`float`、`double`- 字符型:`char`- 枚举型:`enum`2. 解释赋值运算符的左结合性和右结合性。

- 赋值运算符是右结合性,意味着从右向左进行赋值。

第三章:控制语句1. 什么是条件语句?- 条件语句允许程序根据条件是否满足来执行不同的代码路径。

2. 描述循环语句的类型及其用法。

- `for`循环:用于已知迭代次数的循环。

- `while`循环:用于未知迭代次数,条件为真时循环。

- `do-while`循环:至少执行一次循环体,然后检查条件。

第四章:函数1. 函数的定义是什么?- 函数是一段具有特定功能的代码块,可以接收参数并返回值。

2. 解释函数原型和函数定义的区别。

- 函数原型声明了函数的名称、返回类型和参数列表,但不包含函数体。

- 函数定义包含了函数的完整实现,包括函数体。

第五章:数组1. 一维数组的声明和初始化方式。

- 声明:`type arrayName[arraySize];`- 初始化:`int arr[5] = {1, 2, 3, 4, 5};`2. 二维数组的访问方式。

C程序设计教程第二版习题答案

C程序设计教程第二版习题答案

C程序设计教程第二版习题答案第1章:C语言概述1. 简述C语言的特点。

- C语言是一种结构化编程语言,具有高效、灵活、功能强大等特点。

它支持多种编程范式,包括过程式、面向对象和泛型编程。

2. C语言的发展历史。

- C语言由丹尼斯·里奇在20世纪70年代初期开发,最初用于UNIX操作系统的编写。

随着UNIX的流行,C语言也逐渐普及。

第2章:C语言基础1. 变量声明的规则。

- 变量声明必须指定数据类型,变量名必须以字母或下划线开头,可以包含字母、数字和下划线,但数字不能作为变量名的首位。

2. 常量的使用。

- 常量是在程序执行过程中不能被修改的值,可以用#define预处理指令定义,或者直接使用字面量。

第3章:控制语句1. if语句的使用。

- if语句用于根据条件执行不同的代码块。

基本语法为:`if (条件) { 执行代码 }`。

2. switch语句的使用。

- switch语句用于根据变量的值执行不同的代码块。

基本语法为:`switch (变量) { case 值1: 执行代码1; break; ... }`。

第4章:循环语句1. for循环的使用。

- for循环用于重复执行一段代码直到满足特定条件。

基本语法为:`for (初始化; 条件; 增量/减量) { 执行代码 }`。

2. while循环的使用。

- while循环在条件为真时重复执行代码块。

基本语法为:`while (条件) { 执行代码 }`。

第5章:函数1. 函数的定义和调用。

- 函数是一段具有特定功能的代码块,可以被重复调用。

定义函数的基本语法为:`返回类型函数名(参数列表) { 函数体 }`。

调用函数时使用:`函数名(参数)`。

2. 函数的参数传递。

- 参数传递可以是值传递或引用传递。

值传递时,函数内部对参数的修改不会影响到外部变量的值;引用传递则相反。

第6章:数组1. 一维数组的声明和使用。

- 一维数组的声明语法为:`类型数组名[大小]`。

c语言程序设计教程第二版课后答案

c语言程序设计教程第二版课后答案

c语言程序设计教程第二版课后答案【篇一:c语言程序设计(第2版)-- 课后题答案】p> 参考答案第1章进入c语言程序世界二、1.i love china!printf(we are students.\n)2.6项目实训题参考答案1.编写一个c程序,输出以下信息:* * * * * * * * * * * * * * * * * * * *i am a student!* * * * * * * * * * * * * * * * * * * *main(){ printf(********************\n);printf( i am a student!\n);printf(********************\n);}2.已知立方体的长、宽、高分别是10cm、20cm、15cm,编写程序,求立方体体积。

解:main(){int a,b,c,v;a=10;b=20;c=15;v=a*b*c;printf(v=%d,v);}本程序运行结果为:v=3000第2章编制c程序的基础知识一选择题c b a b a c c二操作题,2,-8,23.000000,2.500000,-8.0000002. abc defghwhy is21+35equal 523.34214. aaa项目实训题1.定义一个符号常量m为5和一个变量n值为2,把它们的乘积输出。

#define m 5main(){ int n,c;n=2; c=m*n;printf(%d\n,c);}2.编程求下面算术表达式的值。

(1)x+a%3*(int)(x+y)%2/4,设x=2.5,a=7,y=4.7;(2)(float)(a+b)/2+(int)x%(int)y,设a=2,b=3,x=3.5,y=2.5。

(1)main(){ int a=7;float x=2.5,y=4.7;printf(%f\n,x+a%3*(int)(x+y)%2/4);}(2)main(){ int a=2,b=3;float x=3.5,y=2.5;printf(%f\n,(float)(a+b)/2+(int)x%(int)y);}第三章顺序结构程序设计一选择题a c d c c二操作题1. x=3,a=2,b=32. z=12.7000002 13 3 2 bb cc abc n3. 1 2 1a2 1 2三.编程题编程题解:#include stdio.hmain(){float sj,gz,yfgz;printf(time,salary:);scanf(%f,%f,sj,gz);yfgz=sj*gz*0.9;printf(total salary:%f\n,yfgz);}本程序运行结果为:time,salary:4,3crtotal salary:10.8000002.编写一个程序求出任意一个输入字符的ascii码解:#include stdio.hmain(){char c;printf(input a string:);scanf(%c,c);printf(%c ascii is %d\n,c,c);}本程序运行结果为:input a string:acra ascii is 973、编写一个程序用于水果店售货员算帐:已知苹果每斤2.50元,鸭梨每斤1.80元,香蕉每斤2元,橘子每斤1.6元,要求输入各类水果的重量,打印出应付3解:main(){float p,y,x,j,ys,g,fk;printf(apple,pear,banana,orange(weight)=);scanf(%f,%f,%f,%f,p,y,x,j);ys=2.5*p+1.8*y+2*x+1.6*j;printf(fu kuan=);scanf(%f,g);fk=g-ys;printf(result:\n);printf(fukuan=%6.2fyuan\nshoukuan=%6.2fyuan\nzhaohui=%6. 2fyuan\n,g,ys,fk);}本程序运行结果为:apple,pear,banana,orange(weight)=1,2,3,4fu kuan=100result:fukuan=100.00yuanshoukuan= 18.50yuanzhaohui= 81.50yuan项目实训1.假设银行定期存款的年利率rate为2.25%,并已知存款期为n 年,存款本金为capital元,试编程计算n年后可得到本利之和deposit。

C语言程序设计教程(第2版)课后习题答案(完美版)

C语言程序设计教程(第2版)课后习题答案(完美版)

C语言程序设计教程(第二版)课后习题答案第一章C语言程序设计概述-习题答案1算法的描述有哪些基本方法?答1、自然语言2、专用工具2 C语言程序的基本结构是怎样的?举一个例子说明。

答1、C语言程序由函数构成;2、“/*”与“*/”之间的内容构成C语言程序的注释部分;3、用预处理命令#include、#define可以包含有关文件或预定义信息;4、大小写字母在C语言中是有区别的;5、除main()函数和标准库函数外,用户也可以自己编写函数,应用程序一般由多个函数组成,这些函数指定实际所需要做的工作。

3 C语言有什么特点?答1、具有结构语言的特点,程序之间很容易实现段的共享;2、主要结构成分为函数,函数可以在程序中被定义完成独立的任务,独立地编译代码,以实现程序的模块化;3、运算符丰富,包含的范围很广;4、数据类型丰富;5、允许直接访问物理地址,即可直接对硬件进行损伤,实现汇编语言的大部分功能;6、限制不太严格,程序设计自由度大,这样使C语言能够减少对程序员的束缚;7、生成的目标代码质量,程序执行效率高,同时C语言编写的程序的可移植性好。

4★指出合法与不合法的标识符命名。

答AB12--√leed_3-- a*b2--× 8stu--× D.K.Jon--× EF3_3--√ PAS--√ if--× XYZ43K2 --√ AVE#XY--× _762--√ #_DT5--× C.D--×5说明下列Turbo C热键的功能。

答F2:源文件存盘 F10:调用主菜单 F4:程序运行到光标所在行(用于调试程序) Ctrl+F9:编译并链接成可执行文件 Alt+F5:将窗口切换到 DOS 下,查看程序运行结果。

6说明下列Turbo C方式下输入并运行下列程序,记录下运行结果。

①main(){printf("********************\n");printf(" welcome you \n");printf(" very good \n);printf("********************\n");}②main()printf("please input three numbers;");scanf("%d,%d,%d",&a,&b,&c); /*教材S是错误的*/t=max(max(a,b),c);printf("max number is:%d\n",t);}int max(int x, int y){ int z;if(x>y)z=x;else z=y;return(z);}答运行结果:********************welcome youvery good********************运行结果:please input three numbers;3,1,4 /*左侧下划线内容为键盘输入*/max number is:47一个C程序是由若干个函数构成的,其中有且只能有一个___函数。

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