C语言程序的设计习题参考答案(第二版_杜友福)

合集下载

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语言程序设计教程(第二版)》习题答案

1 【C语言】《C语言程序设计教程(第二版)》习题答案说明1. 本文所指的《C语言程序设计教程(第二版)》是李凤霞主编、北京理工大学出版社出版的,绿皮。

2 第1章程序设计基础知识一、单项选择题(第23页)1-4.CBBC 5-8.DACA二、填空题(第24页)1.判断条件2.面向过程编程3.结构化4.程序5.面向对象的程序设计语言7.有穷性8.直到型循环9.算法10.可读性11.模块化12.对问题的分析和模块的划分三、应用题(第24页)2.源程序:main(){int i,j,k; /* i:公鸡数,j:母鸡数,k:小鸡数的1/3 */printf("cock hen chick\n");for(i=1;i<=20;i++)for(j=1;j<=33;j++)for(k=1;k<=33;k++)if (i+j+k*3==100&&i*5+j*3+k==100)printf(" %d %d %d\n",i,j,k*3);}执行结果:cock hen chick4 18 788 11 8112 4 843.现计算斐波那契数列的前20项。

递推法源程序:main(){long a,b;int i;a=b=1;for(i=1;i<=10;i++) /*要计算前30项,把10改为15。

*/{printf("%8ld%8ld",a,b);a=a+b;b=b+a;}}递归法源程序:main(){int i;for(i=0;i<=19;i++)printf("%8d",fib(i));}fib(int i){return(i<=1?1:fib(i-1)+fib(i-2));}执行结果:1 123 5 8 13 21 34 5589 144 233 377 610 987 1597 2584 4181 6765 4.源程序:#include "math.h";main(){double x,x0,deltax;x=1.5;do {x0=pow(x+1,1./3);deltax=fabs(x0-x);x=x0;}while(deltax>1e-12);printf("%.10f\n",x);}执行结果:1.32471795725.源程序略。

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语言第二版课后习题答案

c语言第二版课后习题答案

c语言第二版课后习题答案C语言第二版课后习题答案C语言是一门广泛应用于计算机科学和软件开发领域的编程语言。

作为一门基础性的编程语言,掌握C语言对于学习其他高级编程语言以及深入理解计算机原理和操作系统等方面都具有重要意义。

而《C语言第二版》是一本经典的C 语言教材,对于初学者来说是一本非常好的入门教材。

在学习C语言过程中,课后习题是巩固知识、提高编程能力的重要环节。

下面,我将为大家提供一些C语言第二版课后习题的答案。

1. 编写一个C程序,实现两个整数相加并输出结果。

```c#include <stdio.h>int main() {int num1, num2, sum;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);sum = num1 + num2;printf("两个整数的和为:%d\n", sum);return 0;}```2. 编写一个C程序,判断一个数是否为偶数。

```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if (num % 2 == 0) {printf("该数为偶数\n");} else {printf("该数为奇数\n");}return 0;}```3. 编写一个C程序,计算一个数的阶乘。

```c#include <stdio.h>int main() {int num, i;long long factorial = 1;printf("请输入一个整数:");scanf("%d", &num);if (num < 0) {printf("负数没有阶乘\n");return 0;}for (i = 1; i <= num; i++) {factorial *= i;}printf("%d的阶乘为:%lld\n", num, factorial);return 0;}```4. 编写一个C程序,判断一个数是否为素数。

c语言程序设计教程(第2版)课后题及模拟题参考答案

c语言程序设计教程(第2版)课后题及模拟题参考答案

c语言程序设计教程(第2版)课后题及模拟题参考答案习题11-1 填空题1.函数2.主函数main(),主函数main()3.主函数main()4.函数首部,函数体5.{, }6./*, */7.顺序结构,选择结构,循环结构8..c, .obj, .exe1-2 思考题1.结构化程序设计是指:为使程序具有一个合理的结构以保证程序正确性而规定的一套如何进行程序设计的原则。

其基本结构包括顺序结构、选择结构和循环结构三种。

2.算法是对具体问题求解步骤的一种描述。

计算机算法的表达工具通常采用以下几种方法:(1)用自然语言表示算(2)用流程图表示算法(3)用伪代码表示算法(4)用程序设计语言表示算法3.语言简洁、紧凑,使用方便、灵活; 支持结构化程序设计;运算符丰富;数据类型丰富;较强的编译预处理功能;C语言的可移植性好;C语言本身既有一般高级语言的优点,又有低级(汇编)语言的特点;语法限制不太严格,程序设计自由度大。

1-3 编程题1. 试参照本章例题编写计算梯形面积的C语言程序,梯形的上底、下底和高分别用a,b,h表示,并用a=10,b=20,h=5测试所编写的程序。

#include "stdio.h"main(){ float a, b, h, s;a=10; b=20;h=5; s=(a+b)*h/2;printf("s=%f\n" , s );}2. 编写程序显示如图1.11所示信息。

图1.11 显示信息#include "stdio.h"main(){ printf("******************************\n");printf("* hello world *\n");printf("******************************\n"); }习题22-1 单选题1~5 DBDCA 6~10 DCABA 11~12 CA 2-2 思考题1.2.0000002.1,0.53.9,24.65.100,d6.(1)20 (2)0 (3)607. (1)10,6,4 (2)6,9,15 (3)3,60,838. 55习题33-1 选择题1-5BDABC 6-10ADCAC 11-12BB3-2 填空题1. 32.02613.0x104. 2, 1 互换a,b的值5. 6.66.–0038.77. 5.0,4,c=3<Enter>8.i=10,j=20<Enter>9.(1) 65(2) 65,A(3) 56.123400,123.456001(4) 3.141600(5) 8765.432(6) 5.864000e+002(7) 3.141600e+000(8) 3.1416(9) 8765(10) 3.1416,8765.4310.a=2 b=5x=8.8 y=76.34c1=65 c2=973-3 编程题1. 编写程序实现从键盘输入两个十进制整型数据10和8给变量x和y,并按下列格式 输出。

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 语言程序设计教程第二版课后习题答案

c 语言程序设计教程第二版课后习题答案C语言程序设计教程第二版课后习题答案C语言是一种广泛使用的计算机编程语言,它在软件开发领域有着广泛的应用。

对于初学者来说,学习C语言程序设计是一个重要的基础。

《C语言程序设计教程》是一本经典的教材,第二版的习题更加丰富多样,有助于学生巩固所学的知识。

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

第一章:C语言概述1. 答案略第二章:C语言基础1. 答案略第三章:运算符和表达式1. 答案略第四章:选择结构1. 答案略第五章:循环结构1. 答案略第六章:数组1. 答案略第七章:函数1. 答案略第八章:指针1. 答案略第九章:字符串1. 答案略第十章:结构体1. 答案略第十一章:文件操作1. 答案略第十二章:位运算1. 答案略以上是《C语言程序设计教程第二版》课后习题的答案。

这些答案只是供参考,可以帮助学生更好地理解和掌握C语言的编程技巧。

然而,作为学习者,我们不能仅仅依赖答案,更重要的是理解其中的原理和思想。

通过自己的思考和实践,才能真正掌握C语言的编程能力。

在学习C语言的过程中,我们还可以通过参考其他资料和教程来进一步提高自己的编程水平。

除了课后习题,我们还可以尝试编写一些小项目,锻炼自己的实际操作能力。

同时,多与他人交流和讨论,互相学习和进步也是非常重要的。

总之,C语言程序设计是一门非常有用的技能,掌握它可以为我们的职业发展和学术研究提供很多帮助。

通过学习《C语言程序设计教程第二版》课后习题的答案,我们可以更好地理解和掌握C语言编程的基础知识。

希望大家在学习过程中能够坚持不懈,不断提高自己的编程能力。

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

c语言程序设计教程第二版课后习题答案1. 基本概念和语法1.1 变量和数据类型题目:请将下列C语言的变量定义语句补充完整,并给出每个变量的数据类型和初始化值。

代码:```c#include <stdio.h>int main() {int a;float b;char c;double d;int x = 5;float y = 3.14;char z = 'A';printf("a的数据类型:%s,a的初始值:%d\n", typeof(a), a);printf("b的数据类型:%s,b的初始值:%f\n", typeof(b), b); printf("c的数据类型:%s,c的初始值:%c\n", typeof(c), c); printf("d的数据类型:%s,d的初始值:%lf\n", typeof(d), d); printf("x的数据类型:%s,x的初始值:%d\n", typeof(x), x); printf("y的数据类型:%s,y的初始值:%f\n", typeof(y), y); printf("z的数据类型:%s,z的初始值:%c\n", typeof(z), z); return 0;}```答案:a的数据类型:int,a的初始值:随机值b的数据类型:float,b的初始值:随机值c的数据类型:char,c的初始值:'\0'd的数据类型:double,d的初始值:随机值x的数据类型:int,x的初始值:5y的数据类型:float,y的初始值:3.140000z的数据类型:char,z的初始值:A1.2 运算符和表达式题目:请在下列C语言程序中补充运算符,使程序达到题目要求。

```c#include <stdio.h>int main() {int a = 5;int b = 3;int c;// 1. 将a和b的和赋值给c,并将c的值输出// 补充代码// 2. 将a和b的差赋值给c,并将c的值输出// 补充代码// 3. 将a和b的积赋值给c,并将c的值输出// 补充代码// 4. 将a除以b的商赋值给c,并将c的值输出// 补充代码// 5. 将a除以b的余数赋值给c,并将c的值输出// 补充代码return 0;}```要求:1. 补充代码,使程序能够正确输出运算结果;2. 使用合适的运算符。

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

c语言程序设计现代方法(第二版)习题答案(5篇)第一篇:c语言程序设计现代方法(第二版)习题答案Chapter 2 Answers to Selected Exercises 2.[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 time available for its completion.3.[was #4] #includeint main(void){ int height = 8, length = 12, width = 10, volume;volume = height * length * width;printf(“Dimensions: %dx%dx%dn”, length, width, height);printf(“Volume(cubic inches): %dn”, volume);printf(“Dimensional weight(pounds): %dn”,(volume + 165)/ 166);return 0;} 4.[was #6] Here's one possible program: #include int main(void){ int i, j, k;float x, y, z;printf(“Value of i: %dn”, i);printf(“Value of j: %dn”, j);printf(“Value of k: %dn”, k);printf(“Value of x: %gn”, x);printf(“Value of y: %gn”, y);printf(“Value of z: %gn”, z);return 0;} When compiled using GCC and then executed, this program produced the following output: Value of i: 5618848 Value of j: 0 Value of k: 6844404 Value of x: 3.98979e-34 Value of y: 9.59105e-39 Value of z: 9.59105e-39 The 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 Projects 4.[was #8;modified] #includeint 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: $%.2fn”, amount_with_tax);return 0;} The amount_with_tax variable is unnecessary.If we remove it, the program is slightly shorter: #includeint main(void){ float original_amount;printf(“Enter an amount: ”);scanf(“%f”, &original_amount);printf(“With tax added: $%.2fn”, original_amount * 1.05f);return 0;}Chapter 3 Answers to Selected Exercises 2.[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 Projects 1.[was #4;modified] #includeint 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%.2dn”, year, month, day);return 0;} 3.[was #6;modified] #includeint 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: %dn”, prefix);printf(“Group identifier: %dn”, group);printf(“Publisher code: %dn”, publisher);printf(“Item number: %dn”, item);printf(“Check digit: %dn”, check_digit);/* The five printf calls can be combined as follows:printf(“GS1 prefix: %dnGroup identifier: %dnPublishercode: %dnItem number: %dnCheck digit: %dn”, prefix, group, publisher, item, check_digit);*/return 0;}Chapter 4 Answers to Selected Exercises 2.[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 0 13.[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 Projects 2.[was #4] #include int main(void){ int n;printf(“Enter a three-digit number: ”);scanf(“%d”, &n);printf(“The reversal is: %d%d%dn”, n % 10,(n / 10)% 10, n / 100);return 0;}Chapter 5 Answers to Selected Exercises 2.[was #2](a)1(b)1(c)1(d)1 4.[was #4](i > j)12, minutes);return 0;} 4.[was #8;modified] #includeint main(void){ int speed;printf(“Enter a wind speed in knots: ”);scanf(“%d”, &speed);if(speed < 1)printf(“Calmn”);else if(speed <= 3)printf(“Light airn”);else if(speed <= 27)printf(“Breezen”);else if(speed <= 47)printf(“Galen”);else if(speed <= 63)printf(“Stormn”);else printf(“Hurricanen”);return 0;} 6.[was #10] #includeint 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 == 91)% 10))printf(“VALIDn”);else printf(“NOT VALIDn”);return 0;} 10.[was #14] #includeint main(void){ int grade;printf(“Enter numerical grade: ”);scanf(“%d”, &grade);if(grade < 0 || grade > 100){ printf(“Illegal graden”);return 0;}switch(grade / 10){ case 10: case 9: printf(“Letter grade: An”);break;case 8: printf(“Letter grade: Bn”);break;case 7: printf(“Letter grade: Cn”);break;case 6: printf(“Letter grade: Dn”);break;case 5: case 4: case 3: case 2: case 1: case 0: printf(“Letter grade: Fn”);break;}return 0;}Chapter 6 Answers to Selected Exercises 4.[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 %dn”, n, d);else printf(“%d is primen”, 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 evenn”);Answers to Selected Programming Projects 2.[was #2] #includeint 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: %dn”, m);return 0;} 4.[was #4] #includeint 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;else commission = 255.00f +.0009f * value;if(commission < 39.00f)commission = 39.00f;printf(“Commission: $%.2fnn”, commission);printf(“Enter value of trade: ”);scanf(“%f”, &value);}return 0;} 6.[was #6] #includeint main(void){ int i, n;printf(“Enter limit on maximum square: ”);scanf(“%d”, &n);for(i = 2;i * i <= n;i += 2)printf(“%dn”, i * i);return 0;} 8.[was #8] #includeint 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 + i1 && y >= 0 && y <= npass;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_CARDS1 && num_in_rank[0] > 0 && num_in_rank[NUM_RANKS-1] > 0){ straight = true;return;}/* check for 4-of-a-kind, 3-of-a-kind, and pairs */ for(rank = 0;rank < NUM_RANKS;rank++){ if(num_in_rank[rank] == 4)four = true;if(num_in_rank[rank] == 3)three = true;if(num_in_rank[rank] == 2)pairs++;} }/********************************************************** * 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(“nn”);}Chapter 11 Answers to Selected Exercises 2.[was #2](e),(f), and(i)are legal.(a)is illegal because p is a pointer to an integer and i is an integer.(b)is illegal because *p is an integer and &i is a pointer to an integer.(c)is illegal because &p is a pointer to a pointer to an integer and q is a pointer to an integer.(d)is illegal for reasons similar to(c).(g)is illegal because p is a pointer to an integer and *q is an integer.(h)is illegal because *p is an integer and q is a pointer to an integer.4.[was #4;modified] void swap(int *p, int *q){ int temp;temp = *p;*p = *q;*q = temp;} 6.[was #6] void find_two_largest(int a[], int n, int *largest, int *second_largest){ int i;if(a[0] > a[1]){ *largest = a[0];*second_largest = a[1];} else { *largest = a[1];*second_largest = a[0];}for(i = 2;i < n;i++)if(a[i] > *largest){ *second_largest = *largest;*largest = a[i];} else if(a[i] > *second_largest)*second_largest = a[i];}Chapter 12 Answers to Selected Exercises 2.[was #2] The statement is illegal because pointers cannot be added.Here's a legal statement that has the desired effect: middle = low +(highlow)/ 2 is an integer, not a pointer, so it can legally be added to low.4.[was #6] int *top_ptr;void make_empty(void){ top_ptr = &contents[0];}bool is_empty(void){ return top_ptr == &contents[0];}bool is_full(void){ return top_ptr == &contents[STACK_SIZE];}6.[was #10;modified] int sum_array(const int a[], int n){ int *p, sum;sum = 0;for(p = a;p < a + n;p++)sum += *p;return sum;} 13.[was #12;modified] #define N 10double ident[N][N], *p;int num_zeros = N;for(p = &ident[0][0];p <= &ident[N-1][N-1];p++)if(num_zeros == N){ *p = 1.0;num_zeros = 0;} else { *p = 0.0;num_zeros++;} 15.[was #14] int *p;for(p = temperatures[i];p < temperatures[i] + 24;p++)printf(“%d ”, *p);Answers to Selected Programming Projects 1.[was #4](a)#include#define MSG_LEN 80 /* maximum length of message */int main(void){ char msg[MSG_LEN];int i;printf(“Enter a message: ”);for(i = 0;i < MSG_LEN;i++){ msg[i] = getchar();if(msg[i] == 'n')break;} printf(“Reversal is: ”);for(i--;i >= 0;i--)putchar(msg[i]);putchar('n');return 0;}(b)#include#define MSG_LEN 80 /* maximum length of message */int main(void){ char msg[MSG_LEN], *p;printf(“Enter a message: ”);for(p = &msg[0];p < &msg[MSG_LEN];p++){ *p = getchar();if(*p == 'n')break;} printf(“Reversal is: ”);for(p--;p >= &msg[0];p--)putchar(*p);putchar('n');return 0;} 3.[was #8] #include#define MSG_LEN 80 /* maximum length of message */int main(void){ char msg[MSG_LEN], *p;printf(“Enter a message: ”);for(p = msg;p < msg + MSG_LEN;p++){ *p = getchar();if(*p == 'n')break;}printf(“Reversal is: ”);for(p--;p >= msg;p--)putchar(*p);putchar('n');return 0;}Chapter 13 Answers to Selected Exercises 2.[was #2](a)Illegal;p is not a character.(b)Legal;output is a.(c)Legal;output is abc.(d)Illegal;*p is not a pointer.4.[was #4](a)int read_line(char str[], int n){ int ch, i = 0;while((ch = getchar())!= 'n')if(i == 0 && isspace(ch));/* ignore */ else if(i < n)str[i++] = ch;str[i] = '';return i;}(b)int read_line(char str[], int n){ int ch, i = 0;while(!isspace(ch = getchar()))if(i < n)str[i++] = ch;str[i] = '';return i;}(c)int read_line(char str[], int n){ int ch, i = 0;do { ch = getchar();if(i < n)str[i++] = ch;} while(ch!= 'n');str[i] = '';return i;}(d)int read_line(char str[], int n){ int ch, i;for(i = 0;i < n;i++){ ch = getchar();if(ch == 'n')break;str[i] = ch;} str[i] = '';return i;} 6.[was #6] void censor(char s[]){ int i;for(i = 0;s[i]!= '';i++)if(s[i] == 'f' && s[i+1] == 'o' && s[i+2] =='o')s[i] = s[i+1] = s[i+2] = 'x';} Note that the short-circuit evaluation of && prevents the if statement from testing characters that follow the null character.8.[was #10] tired-or-wired? 10.[was #12] The value of q is undefined, so the call of strcpy attempts to copy the string pointed to by p into some unknown area of memory.Exercise 2 in Chapter 17 discusses how to write this function correctly.15.[was #8](a)3(b)0(c)The length of the longest prefix of the string s that consists entirely of characters from the string t.Or, equivalently, the position of the first character in s that is not also in t.16.[was #16] int count_spaces(const char *s){ int count = 0;while(*s)if(*s++ == ' ')count++;return count;} Answers to Selected Programming Projects 1.[was #14] #include #include #define WORD_LEN 20void read_line(char str[], int n);int main(void){ char smallest_word[WORD_LEN+1], largest_word[WORD_LEN+1], current_word[WORD_LEN+1];printf(“Enter word: ”);read_line(current_word, WORD_LEN);strcpy(smallest_word, strcpy(largest_word, current_word));while(strlen(current_word)!= 4){ printf(“Enter word: ”);read_line(current_word, WORD_LEN);if(strcmp(current_word, smallest_word)< 0)strcpy(smallest_word, current_word);if(strcmp(current_word, largest_word)> 0)strcpy(largest_word, current_word);} printf(“nSmallest word: %sn”, smallest_word);printf(“Largest word:%sn”, largest_word);return 0;}void read_line(char str[], int n){ int ch, i = 0;while((ch = getchar())!= 'n')if(i < n)str[i++] = ch;str[i] = '';} 4.[was #18] #includeint main(int argc, char *argv[]){ int i;for(i = argc-1;i > 0;i--)printf(“%s ”, argv[i]);printf(“n”);return 0;} 6.[was #20] #include #include #include#define NUM_PLANETS 9int string_equal(const char *s, const char *t);int main(int argc, char *argv[]){ char *planets[] = {“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”, “Saturn”, “Uranus”, “Neptune”, “Pluto”};int i, j;for(i = 1;i < argc;i++){ for(j = 0;j < NUM_PLANETS;j++)if(string_equal(argv[i],planets[j])){ printf(“%s is planet %dn”, argv[i], j + 1);break;} if(j == NUM_PLANETS)printf(“%s is not a planetn”, argv[i]);} return 0;}int string_equal(const char *s, const char *t){ int i;for(i = 0;toupper(s[i])== toupper(t[i]);i++)if(s[i] == '')return 1;return 0;}Chapter 14 Answers to Selected Exercises 2.[was #2] #define NELEMS(a)((int)(sizeof(a)/ sizeof(a[0])))4.[was #4](a)One problem stems from the lack of parentheses around the replacement list.For example, the statement a = 1/AVG(b, c);will be replaced by a = 1/(b+c)/2;Even if we add the missing parentheses, though, the macro still has problems, because it needs parentheses around x and y in the replacement list.The preprocessor will turn the statement a = AVG(bd);into a =((bd)/2);which is equivalent to a =((bd)/2);Here's the final(corrected)version of the macro: #define AVG(x,y)(((x)+(y))/2)(b)The problem is the lack of parentheses around the replacement list.For example, a = 1/AREA(b, c);becomes a = 1/(b)*(c);Here's the corrected macro: #define AREA(x,y)((x)*(y))5.[was #6](a)The call of putchar expands into the following statement: putchar(('a'<=(s[++i])&&(s[++i])<='z'?(s[++i])-'a'+'A':(s[++i])));The character a is less than or equal to s[1](which is b), yielding a true condition.The character s[2](which is c)is less than or equal to z, which is also true.The value printed is s[3]-'a'+'A', which is D(assuming that the character set is ASCII).(b)The character a is not less than or equal to s[1](which is 1)so the test condition is false.The value printed is s[2], which is 2.7.[was #8](a)long long_max(long x, long y){ return x > y ? x : y;} The preprocessor would actually put all the tokens on one line, but this version is more readable.(b)The problem with types such as unsigned long is that they require two words, which prevents GENERIC_MAX from creating the desired function name.For example, GENERIC_MAX(unsigned long)would expand intounsigned long unsigned long_max(unsigned long x, unsigned long y){ return x > y ? x : y;}(c)To make GENERIC_MAX work with any basic type, use a type definition to rename the type: typedef unsigned long ULONG;We can now write GENERIC_MAX(ULONG).12.[was #10](c)and(e)will fail, since M is defined.14.[was #12;modified] Here's what the program will look like after preprocessing: Blank line Blank line Blank line Blank line Blank line Blank line Blank lineint main(void){ int a[= 10], i, j, k, m;Blank line i = j;Blank line Blank line Blank linei = 10 * j+1;i =(x,y)x-y(j, k);i =((((j)*(j)))*(((j)*(j))));i =(((j)*(j))*(j));i = jk;puts(“i” “j”);Blank line i = SQR(j);Blank line i =(j);return 0;} Some preprocessors delete white-space characters at the beginning of a line, so your results may vary.Three lines will cause errors when the program is compiled.Two contain syntax errors: int a[= 10], i, j, k, m;i =(x,y)x-y(j, k);The third refers to an undefined variable: i = jk;Chapter 15 Answers to Selected Exercises 2.[was #2](b).Function definitions should not be put in a header file.If a function definition appears in a header file that is included by two(or more)source files, the program can't be linked, since the linker will see two copies of the function.6.[was #8](a)main.c, f1.c, and f2.c.(b)f1.c(assuming that f1.h is not affected by the change).(c)main.c, f1.c, and f2.c, since all three include f1.h.(d)f1.c and f2.c, since both include f2.h.Chapter 16 Answers to Selected Exercises 2.[was #2;modified](a)struct { double real, imaginary;} c1, c2, c3;(b)struct { double real, imaginary;} c1 = {0.0, 1.0}, c2 = {1.0, 0.0}, c3;(c)Only one statement is necessary: c1 = c2;(d)c3.real = c1.real + c2.real;c3.imaginary = c1.imaginary +c2.imaginary;4.[was #4;modified](a)typedef struct { double real, imaginary;} Complex;(b)Complex c1, c2, c3;(c)Complex make_complex(double real, double imaginary){ Complex c;c.real = real;c.imaginary = imaginary;return c;}(d)Complex add_complex(Complex c1, Complex c2){ Complex c3;c3.real = c1.real + c2.real;c3.imaginary = c1.imaginary + c2.imaginary;return c3;} 11.[was #10;modified] The a member will occupy 8 bytes, the union e will take 8 bytes(the largest member, c, is 8 bytes long), and the array f will require 4 bytes, so the total space allocated for s will be 20 bytes.14.[was #12;modified](a)double area(struct shape s){ if(s.shape_kind == RECTANGLE)return s.u.rectangle.height * s.u.rectangle.width;else return 3.14159 * s.u.circle.radius * s.u.circle.radius;}(b)struct shape move(struct shape s, int x, int y){ struct shape new_shape = s;new_shape.center.x += x;new_shape.center.y += y;return new_shape;}(c)struct shape scale(struct shape s, double c){ struct shape new_shape = s;if(new_shape.shape_kind == RECTANGLE){ new_shape.u.rectangle.height *= c;new_shape.u.rectangle.width *= c;} else new_shape.u.circle.radius *= c;return new_shape;} 15.[was #14](a)enum week_days {MON, TUE, WED, THU, FRI, SAT, SUN};(b)typedef enum {MON, TUE, WED, THU, FRI, SAT, SUN} Week_days;17.[was #16] All the statements are legal, since C allows integers and enumeration values to be mixed without restriction.Only(a),(d), and(e)are safe.(b)is not meaningful if i has a value other than 0 or 1.(c)will not yield a meaningful result if b has the value 1.Answers to Selected Programming Projects 1.[was #6;modified] #include#define COUNTRY_COUNT((int)(sizeof(country_codes)/sizeof(country_codes[0])))struct dialing_code { char *country;int code;};const struct dialing_code country_codes[] = {{“Argentina”, 54}, {“Bangladesh”, 880}, {“Brazil”, 55}, {“Burma(Myanmar)”, 95}, {“China”, 86}, {“Colombia”, 57}, {“Congo, Dem.Rep.of”, 243}, {“Egypt”, 20}, {“Ethiopia”, 251}, {“France”, 33}, {“Germany”, 49}, {“India”, 91}, {“Indonesia”, 62}, {“Iran”, 98}, {“Italy”, 39}, {“Japan”, 81}, {“Mexico”, 52}, {“Nigeria”, 234}, {“Pakistan”, 92}, {“Philippines”, 63}, {“Poland”, 48}, {“Russia”, 7}, {“South Africa”, 27}, {“South Korea”, 82}, {“Spain”, 34}, {“Sudan”, 249}, {“Thailand”, 66}, {“Turkey”, 90}, {“Ukraine”, 380}, {“United Kingdom”, 44}, {“United States”, 1}, {“Vietnam”, 84}};int main(void){ int code, i;printf(“Enter dialing code: ”);scanf(“%d”, &code);for(i = 0;i < COUNTRY_COUNT;i++)if(code == country_codes[i].code){ printf(“The country with dialing code %d is %sn”, code, country_codes[i].country);re turn 0;} printf(“No corresponding country foundn”);return 0;} 3.[was #8] #include #include “readline.h”#define NAME_LEN 25 #define MAX_PARTS 100struct part { int number;char name[NAME_LEN+1];int on_hand;};int find_part(int number, const struct part inv[], int np);void insert(struct part inv[], int *np);void search(const struct part inv[], int np);void update(struct part inv[], int np);void print(const struct part inv[], int np);/********************************************************** * main: Prompts the user to enter an operation code, * * then calls a function to perform the requested * * action.Repeats until theuser enters the * * command 'q'.Prints an error message if the user * * enters an illegal code.* **********************************************************/ int main(void){ char code;struct part inventory[MAX_PARTS];int num_parts = 0;for(;;){ printf(“Enter operation code: ”);scanf(“ %c”, &code);while(getchar()!= 'n')/* skips to end of line */;switch(code){ case 'i': insert(inventory, &num_parts);break;case 's': search(inventory, num_parts);break;case 'u': update(inventory, num_parts);break;case 'p': print(inventory, num_parts);break;case 'q': return 0;default: printf(“Illegal coden”);} printf(“n”);} } /********************************************************** * find_part: Looks up a part number in the inv array.* * Returns the array index if the part number * * is found;otherwise, returns-1.* **********************************************************/ int find_part(int number, const struct part inv[], int np){ int i;for(i = 0;i < np;i++)if(inv[i].number == number)return i;return-1;}/********************************************************** * insert: Prompts the user for information about a new * * part and then inserts the part into the inv * * array.Prints an error message and returns * * prematurely if the part already exists or the * * array is full.* **********************************************************/ void insert(struct part inv[], int *np){ int part_number;if(*np == MAX_P ARTS){ printf(“Database is full;can't add more parts.n”);return;}printf(“Enter part number: ”);scanf(“%d”, &part_number);if(find_part(part_number, inv, *np)>= 0){ printf(“Part already exists.n”);return;}inv[*np].number = part_number;printf(“Enter part na me: ”);read_line(inv[*np].name, NAME_LEN);printf(“Enter quantity on hand: ”);scanf(“%d”, &inv[*np].on_hand);(*np)++;} /********************************************************** * search: Prompts the user to enter a part number, then * * looks up the part in the inv array.If the * * part exists, prints the name and quantity on * * hand;if not, prints an error message.* **********************************************************/ void search(const struct part inv[], int np){ int i, number;printf(“Enter part number: ”);scanf(“%d”, &number);i = find_part(number, inv, np);if(i >= 0){ printf(“Part name: %sn”, inv[i].name);printf(“Quantity on hand: %dn”, inv[i].on_hand);} else printf(“Part not found.n”);}/********************************************************** * update: Prompts the user to enter a part number.* * Prints an error message if the part can't be * * found in the inv array;otherwise, prompts the * * user to enter change in quantity on hand and * * updates the array.* **********************************************************/ void update(struct part inv[], int np){ int i, number, change;printf(“Enter part number: ”);scanf(“%d”, &number);i = find_part(number, inv, np);if(i >= 0){ printf(“Enter change in quantity on hand: ”);scanf(“%d”, &change);inv[i].on_hand += change;} else printf(“Part not found.n”);}/********************************************************** * print: Prints a listing of all parts in the inv array, * * showing the part number, part name, and * * quantity on hand.Parts are printed in the * * order in which they were entered into the * * array.* **********************************************************/ void print(const struct part inv[], int np){ int i;printf(“Part Number Part Name ” “Quantity on Handn”);for(i = 0;i < np;i++)printf(“%7d %-25s%11dn”, inv[i].number, inv[i].name, inv[i].on_hand);}Chapter 17 Answers to Selected Exercises 2.[was #2;modified] char *duplicate(const char *s){ char *temp = malloc(strlen(s)+ 1);if(temp == NULL)return NULL;strcpy(temp, s);return temp;} 5.[was #6](b)and(c)are legal.(a)is illegal because it tries to reference a member of d without mentioning d.(d)is illegal because it uses-> instead of.to reference the c member of d.7.[was #8] The first call of free will release the space for the first node in the list, making p a dangling pointer.Executing p = p->next to advance to the next node will have an undefined effect.Here's a correct way to write the loop, using a temporary pointer that points to the node being deleted: struct node *temp;p = first;while(p!= NULL){ temp = p;p = p->next;free(temp);} 8.[was #10;modified] #include /* C99 only */ #include #include #include “stack.h”struct node { int value;struct node *next;};struct node *top = NULL;void make_empty(void){ struct node *temp;第二篇:《C语言程序设计教程(第二版)》习题答案《C语言程序设计教程(第二版)》习题答案说明1.本习题答案是我自己做的,错误和疏漏在所难免。

C语言程序设计(第2版)-- 课后题答案-推荐下载

《C 语言程序设计能力教程(第二版)》课后作业及实训题
参考答案
第 1 章 进入 C 语言程序世界 二、 1. I love China!
printf("we are students.\n") 2. 6 项目实训题参考答案
1.编写一个 C 程序,输出以下信息: ******************** I am a student! ********************
ቤተ መጻሕፍቲ ባይዱ:
4
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");
float rate=0.0225,capital,deposit; scanf("%d,%f",&n,&capital); deposit=capital*pow(1+rate,n); printf("deposit=%f\n",deposit); } 2.将一个三位数整数,正确分离出它的个位、十位和百位数字,并分别在屏幕上 输出。 main() { int n,a,b,c; scanf("%3d",&n); a=n/100; b=n%100/10; c=n%100%10/1;
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C 语言程序设计习题答案习题一 C 语言程序设计概述一、 名词解释(1)程序P1 (2)程序设计P1(3)机器语言P1(4)汇编程序P2 (5)高级语言P2 (6)编译程序P3 (7)解释程序P3 (8)算法P4(9)结构化的程序设计P9二、 简述题1.设计程序时应遵循哪些基本原则? P4答:正确性、可靠性、简明性、有效性、可维护性、可移植性。

2.算法的要素是什么?算法具有哪些特点?答:算法的要素是:操作与控制结构;算法的特点有:有穷性、确左性、有效性、有零个或多个输入、有一个或多个输出。

3.算法的表示形式有哪几种?答:算法的表示形式有:自然语言、传统流程图、伪代码、结构化的流程图(N_S 流程图,盒图)。

4.有哪三种基本结构?答:三种基本结构是:顺序结构、选择结构和循环结构。

5.传统流程图与N-S 流程图最大的区别是什么?答:N-S 流程图去掉了在传统流程图中常用的流程线,使得程序的结构显得更加淸晰、简单。

三、 用传统流程图、N-S 图分别表示求解以下问题的算法。

1.有3个数a, b, c,要求按由大到小的顺序把它们输出。

2.依次将10个数输入,求岀其中最大的数 和最小的数并输岀。

3.求 1+2+3+-+100 的值。

输入一个数给Xmax=x:min=x;n=l;当n 小于10时输入下一个数给X如果 max<xmax = x如果 min>xNomin = xn = n + 1输岀max,min 的值4.求 1X2X3X-X10 的值。

7.求一元二次方程ax'+bx+c 二0的根。

分别考虑d=b-4ac 大于0.等于0和小于0三种情况。

四、注释下面C 程序的各个组成部分。

mainO {/*主函数*//*程序开始*/int a, k, m; 3=10;/*左义三个用来存放整数的变量*/ /*将整数10赋值给变量a */ 22; m=l; /*将整数2赋值给变量k ♦//*将整数1赋值给变量1 */a= (k+m) *k/ (k-m); printf (,z %d\n /z , a);}/*先求出算术表达式的值,并将其赋值给变量a /*在屏幕上打印出变量a 的值*/ /*程序结朿*/习题二数据类型、运算符与表达式一.选择题1 〜10: BCDCB DDBCA 11-20: ADDAADBADC 21~28:DABADCDD5.求下列分段函数的值。

「3X4X-1 5(X-l)+6 (X<1) (X=l) (1<X<5) 6-3X(X>5)6.求100-200之间的所有素数。

i=100当i<=200时n=2; flag=l;当nv i 时否被n 整|愛/yes flag=On = n+1flag= 1 ?yesno输出i 的i = i+13=0一~ * 假非二次 方程---------------------- -相等实根 -b/2ab p =-—2a 口 _ -4ac2a -4ac)q = -_;------------lar -d - y/b 2_ 4ac vH —AZ-2a两次根:xK x2复根:p 十qi p-qi二填空题1. 字母L 或字母12.字符或%c 、 整数或%d3・在程序运行过程中,其值可以在一左的阳变化的量。

7・ 字母、 数字、 卜划线、 数宝8. 18 9. 2、1 3010. 双精度实数或double 11. 賦值、 逗号、20. 20、 20、412.4习题三顺序程序设计一、 选择题1 〜10: BCCBC CCDCC二、 填空题1. printf() > scanf()2. 1 (注:long 的第1个字符)3. 域宽,即在格式字符前加一个整数,如%5d4.9三、编程题1.编写程序,从键盘输入一个以秒为单位的时间数,将其换算成几小时几分几秒,然后进 行输出。

例如输入的时间为4258秒,则输岀结果为:1小时10分58秒。

答:程序参见文件Cprogram\xt3_3_01 .c#include n stdio.h M main() {int x,h,m,s; scanf(,,%d ,\&x);h=x/3600; m=x%3600/60; s=x%60; printf(H %ds=%d:%d:%d!\n ,\x,h,m,s);4.5. 6‘\0,小数形式 关键字指数形式 预定义标识符用户标识符2.编写程序,读入三个整数给变量a、b、c・然后交换它们中的数,把a中原来的值给b, 把b中原来的值给c,把c中原来的值给氛答:程序参见文件Cprogram\xt3_3_02.c#include H stdio.h Mmain(){int a.bx,t;printf(H i nput a b c:,r); scanf(M%d%d%d,\&a.&b,&c); printf(M a=%d,b=%dx=%d\n'\a,bx); t=a;a=c:c=b;b=t;printf(H a=%d,b=%dx=%d\n,\a,b,c);习题四选择结构程序设计一、填空题1・ 1 02.! % + v二匕 && II =3.x=04.0.25.20 . 0 ()二、选择题1-7: DDCAD DC三、程序阅读题1.5959592.0.5000003・1_4.2_5.6_6.a=2、b=l7.pass& J_四、编程题1.设a为整型变量且英值大于零,请将以下if语句改写成switch语句。

if ( a<60) m=1;else if(a<70) m=2;else if(a<80) m=3;else if(a<90) m=4;else m=5;答:程序参见文件Cprogram\xt4_4_l.c 或Cprogram\xt4_4_ 1 b.c#include w stdio.h Hmain(){int a,m;scanf(n%d M,&a);switch(a/10){case 0:case 1:case 2:case 3:case 4:case 5:m=1 ;break;case 6:m=2;break;case 7:m=3;break;case 8:m=4;break;default:m=5;break;}printf(w m=%d\n H,m);)Cprogram\xt4_4_1 b.c#include ”stdio.h"main(){int a,m;scanf(・%cT,&a);m=0;switch(a/10){default:m++;case 8:m++;case 7:m++;case 6:m++;case 5:case 4:case 3:case 2:case 1:case 0:m++;} printf(M m=%d\n,\m);}2.编写程序,从键盘输入一个整数,打印出它是奇数还是偶数。

答:程序参见文件Cprogram\xt4_4_2.c#include H stdio.h Hmain(){int a;scanf(H%d M,&a);if(a%2==1)printf(H%d is a odd number !\n H,a);elseprintf(H%d is a even number !\n M,a);}3.编写程序,从键盘输入一个字符,判别它是否是小写字母,如果是,将它转换为大写字母:如果不是, 不转换。

然后输出最后得到的字符。

答:程序参见文件Cprogram\x(4_4_3.c#include "stdio.h”main(){char ch;scanf(H%c M,&ch);if(ch>=a, && ch<=,z,)ch=ch-32;printf(M%c\n M,ch);}4.编写程序,从键盘输入一个不多于4位的正整数,打印出它是几位数。

答:程序参见文件Cprogram\xt4_4_4.c#include "stdio.h”main(){int x,n;scanf(”%cf,&x);if(x>1000) n=4;else if(x>100) n=3;else if(x>10) n=2; else n=1;printf(”%d\rT,n);}5.当一个人的月收入在2000元以下时免税;月收入在2000元到5000元之间时,超过2000的部分纳税8%;月收入在5000元以上时,2000至5000之间的部分纳税8%,超过5000的部分纳税15%。

编写程序从键盘输入月收入income,计算并输出应交税款tax。

答:程序参见文件Cprogram\xt4_4_5.c# include H stdio.h Hmain(){int in come;float tax;scanf(”%cT,&income);if(income<=2000)tax=O;else if(income<=5000)tax=0.08*(income-2000);else tax=0.08w(5000-2000)+0.15*(income-5000);tax);printf(M tax=%f\n w1}6.回文是指正读和反读都一样的数或字符串。

例如:12321、55455、35553等都是回文。

请编写一个程序, 从键盘上读取一个包含五位数字的长整数,并判断它是否是回文。

(提示:用除法运算和求余运算把一个数的个位、十位、百位、千位等分别分离岀来。

)答:程序参见文件Cprogram\x(4_4_6.c#include "stdio.h”main(){long x;int a,b,d,e;scanf(”%ld”,&x);a=x/10000; b=x%10000/1000;d=x%100/10; e=x%10;if(a==e && b==d)printf(f,%ld is huiwen!\n M,x);elseprintf(”%ld is not huiwen!\n”,x);}习题五循坏结构程序设计一、阅读题1.8 ____________2.4321 _________3・X4. -15.236.52 __________7. 5 __________8. 3 __________二、填空题1. 182. 23.b=i+l4.175・iv=9 、i%3!=06.d=l.() 、k=k+l ____ 、k v= 1()三、选择题1 〜& ADDAB DDA四、编程题1.编写程序,打印岀所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字的立方之和等于该数本身。

相关文档
最新文档