C语言程序设计现代方法(第二版)习题答案
C语言程序设计现代方法第2版课后习题答案

C语⾔程序设计现代⽅法第2版课后习题答案C语⾔程序设计:现代⽅法[美]K. N. King 著课后习题答案C语⾔的经典之作“近10年来*好的⼀部C语⾔著作”讨论了标准C和C标准库的全部特性强调扫⼀扫⽂末在⾥⾯回复答案+C语⾔程序设计:现代⽅法⽴即得到答案软件⼯程和现代编程理念突出⼯业界的**实践、实际经验和编程风格已被包括哈佛⼤学、⿇省理⼯学院、斯坦福⼤学等全球200多所学校采⽤为教材时⾄今⽇,C语⾔仍然是计算机领域的通⽤语⾔之⼀,但今天的C语⾔已经和初的时候⼤不相同了。
本书主要的⼀个⽬的就是通过⼀种“现代⽅法”来介绍C语⾔,书中强调标准C,强调软件⼯程,不再强调“⼿⼯优化”。
这⼀版中紧密结合了C99标准,并与C89标准进⾏对照,补充了C99中的*特性。
本书分为C语⾔的基础特性、C语⾔的⾼级特性、C语⾔标准库和参考资料4个部分。
每章末尾都有⼀个“问与答”⼩节给出⼀系列与该章内容相关的问题及答案,此外还包含适量的习题。
本书是为⼤学本科阶段的C语⾔课程编写的教材,同时也⾮常适合作为其他课程的辅助⽤书。
K. N. King 世界知名的计算机程序设计教育家,现为佐治亚州⽴⼤学数学与计算机科学系副教授。
他拥有耶鲁⼤学计算机科学硕⼠学位,加州⼤学伯克利分校计算机科学博⼠学位,曾任教于佐治亚理⼯学院。
除本书外,他还撰写了⼴受欢迎的著作Modula-2: A Complete Guide 和Java Programming: From the Beginning,并在Dr.Dobb's Journal等权威杂志上发表了许多⽂章。
业余时间,King教授还在多部电影中扮演过⾓⾊。
⽬ 录第1章 C语⾔概述 11.1 C语⾔的历史 11.1.1 起源 11.1.2 标准化 11.1.3 基于C的语⾔ 21.2 C语⾔的优缺点 31.2.1 C语⾔的优点 31.2.2 C语⾔的缺点 31.2.3 ⾼效地使⽤C语⾔ 4问与答 5第2章 C语⾔基本概念 7显⽰全部信息“我完全沉浸在阅读的过程中,我迫切地想⽤这本书作为授课教材。
C语言程序设计(第二版)习题参考答案

0xf16 10L
1.414E+2
‘\a’
‘\\’
e1 ‘\a’
0128
o7o8 ‘\009’
10L
三、指出下列各项中哪些是 C 语言中的用户标识符
x_1
X_2
High
printf
e2
-e2
count
Int
sizeof IF
sum_12 _123#
解:C 的用户标识符有:x_1 X_2 High
next_ IF sum_12
β
3DS
number $23
NO1:
double
e2 count Int
i/j next_ for
number
四、单项选择题
1.C 语言中,char 型数据在内存中的存储形式是( )。
A.原码
B.反码
C.补码
D.ASCII 码
2.若有定义语句“char c='\72';”则变量 c( )。
A.包含 1 个字符 B.包含 2 个字符 C.包含 3 个字符 D.定义不合法
{ float a,b,c,mindata;
printf("请输入二个数:\n");
scanf("%f %f",&a,&b);
mindata=min(a,b);
printf("较小数:%f\n",mindata);
}
*4.仿照例 1.2 编程,输入 a、b 后,输出一元一次方程 ax+b=0 的解。
。
解:$153.45 \n
2.int i=123;float x= – 1234.56789;
C语言程序设计(第二版)习题参考答案

十进制数
。
A. 112
B. 120
C. 121
D. 122
3.关于 ASCII 码,在计算机中的表示方法准确地描述是
。
A. 使用 8 位二进制数,最右边一位为 1
B. 使用 8 位二进制数,最左边一位为 1
C. 使用 8 位二进制数,最右边一位为 0
D. 使用 8 位二进制数,最左边一位为 0
4.设在机器字长 4 位,X=0111B,Y=1011B,则下列逻辑运算中,正确的是___________。
解:#include <stdio.h> void main() { printf("*****************************\n"); printf(" Merry Christmas!\n");
printf("%f",z);
1
printf("
Happy New Year!\n");
printf("%d*%d=%d\n",a,a,z);
}
*3.仿照例 1.3 编程,输入两个数后,输出其中较小值。
解:#include<stdio.h>
float min(float x, float y)
{ float m;
if (x<y) m=x;
else m=y;
return m;
}
void main()
。
解:bA
4.int a=98;
语句“printf(“%d,%c,%o,%x”,a,a+1,a+2,a+3);”的输出结果是
。
解:98,c,144,65
c语言程序设计第2版习题答案

c语言程序设计第2版习题答案C语言程序设计是计算机科学与技术专业中非常重要的一门基础课程,它涵盖了计算机程序设计的基本原理和方法。
《C语言程序设计》第2版是一本经典的教材,它为学习者提供了大量的习题,帮助他们巩固所学的知识。
本文将为读者提供一些《C语言程序设计》第2版习题的参考答案,希望对读者的学习有所帮助。
第一章:C语言概述1. 什么是C语言?C语言是一种通用的高级程序设计语言,由贝尔实验室的Dennis M. Ritchie于1972年开发。
它具有简洁、高效、灵活的特点,被广泛应用于系统软件、嵌入式系统、游戏开发等领域。
2. C语言的特点有哪些?C语言具有以下特点:- 结构化:C语言支持模块化和结构化的程序设计,使得程序的开发和维护更加方便。
- 高效:C语言的执行效率高,生成的机器码运行速度快。
- 可移植性:C语言编写的程序可以在不同的计算机平台上运行,具有很强的可移植性。
- 强大的库支持:C语言拥有丰富的库函数,可以方便地完成各种操作。
第二章:基本数据类型、运算符和表达式1. C语言的基本数据类型有哪些?C语言的基本数据类型包括整型、字符型、浮点型和指针类型。
其中,整型包括int、short、long和char等;浮点型包括float和double;指针类型用于存储内存地址。
2. 请编写一个程序,交换两个变量的值。
```c#include <stdio.h>void swap(int* a, int* b) {int temp = *a;*a = *b;*b = temp;}int main() {int x = 5;int y = 10;printf("交换前:x = %d, y = %d\n", x, y);swap(&x, &y);printf("交换后:x = %d, y = %d\n", x, y);return 0;}```第三章:控制语句1. 请编写一个程序,判断一个数是否为素数。
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语言程序设计教程第二版课后习题答案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程序设计(第二版)课后习题答案

C 语言程序设计(第二版) 课后习题参考答案
putchar(c2);//将变量 c2 的值输出 printf("\n"); printf("%c%c\n",c1,c2);//用 printf 输出 c1、c2 的值 printf("%d,%d\n",c1,c2);//输出 c1,c2 的 ASCII 码 } 第四章 【习题 4.5】 /*有三个整数 a,b,c,由键盘输入,输出其中最大的数,请编程序。*/ /*变量:三个整数 a、b、c,中间变量 t,最大值 max*/ #include<stdio.h> void main() { int a,b,c,t,max; printf("please input a,b,c:\n"); scanf("%d,%d,%d",&a,&b,&c); t=a>b?a:b;//比较 a 与 b 的大小,将大者赋给中间变量 t max=t>c?t:c;//比较 t 与 c 的大小,将大者赋给最大值 max printf("the max is:\n"); printf("%d\n",max); } 【习题 4.6】 /*给出一百分制成绩,要求输出成绩等级'A'、'B'、'C'、'D'、'E'。90 分以上为'A',80~89 分为 'B',70~79 分为'C',60~69 分为'D',60 分以下为'E'。*/ #include<stdio.h> void main() { int score; printf("please input the score:(0-100)\n"); scanf("%d",&score); if(score>=90&&score<=100) printf("A");//如果成绩大于 90 分,输出 A else if(score>=80&&score<=89) printf("B");//如果成绩在 80~89 之间,输出 B else if(score>=70&&score<=79) printf("C");//如果成绩在 70~79 之间,输出 C else if(score>=60&&score<=69) printf("D");//如果成绩在 60~69 之间,输出 D else printf("E");//成绩小于 60 分时,输出 E printf("\n"); } 【习题 4.7】 /*给一个不多于 5 位的正整数,要求:(1)求出它是几位数;(2)分别输出每一个数字;(3)按 逆顺序输出各位数字,例如原数为 321,应输出 123.*/ /*变量:正整数 x、万位数 a、千位位数 b、百位数 c、十位数 d、个位数 e*/ #include <stdio.h>
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语言程序设计现代方法第二版习题答案CProgramming_AModernApproach

Answers 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 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;}Answers 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\nPublisher code: %d\nItem number: %d\nCheck digit: %d\n", prefix, group, publisher, item, check_digit);*/return 0; }Answers 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 in f exceeds the largest value of type int.Answers to Selected Programming Projects 1. [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 makesure that its elements have type t .)2. [was #8] To use a digit d (in character form) as a subscript into thearray 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.00 int 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 is year % 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 nis greater than 0. (We also assume that digits have consecutive codes in the underlying character set.) For example:Enter a number: 53 Output of pb: 110101A trace of pb's execution would look like this:pb(53) finds that 53 is not equal to 0, so it calls pb(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 callspb(6), which finds that 6 is not equal to 0, so it calls pb(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, soit returns, causingpb(1) to print 1 and return, causing pb(3) to print 1 and return, causing pb(6) to print 0 and return, causing pb(13) to print 1 andreturn, causing pb(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 10 | ___ | ___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 by looking 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");printf("Flush"); printf("Straight"); 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;}else if (flush)else if (straight) else if (three)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;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");else if (card_exists[rank][suit]) printf("Duplicate card; ignored.\n");else { num_in_rank[rank]++; num_in_suit[suit]++; card_exists[rank][suit] = true;cards_read++;}}} /*********************************************************** analyze_hand: Determines whether the hand contains a* straight, a flush, four-of-a-kind, *。
谭浩强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 语言程序设计教程第二版课后习题答案C语言程序设计教程第二版课后习题答案在学习C语言程序设计的过程中,课后习题是巩固知识、提高编程能力的重要环节。
本文将为大家总结C语言程序设计教程第二版课后习题的答案,希望对大家的学习有所帮助。
第一章课后习题答案1.1 编写一个C程序,输出"Hello, World!"。
```c#include <stdio.h>int main() {printf("Hello, World!\n");return 0;}```1.2 编写一个C程序,计算并输出5的阶乘。
```c#include <stdio.h>int main() {int i, fact = 1;for (i = 1; i <= 5; i++) {fact *= i;}printf("5的阶乘为%d\n", fact);return 0;}```1.3 编写一个C程序,输入一个整数n,计算并输出1到n的和。
```c#include <stdio.h>int main() {int n, sum = 0, i;printf("请输入一个整数:");scanf("%d", &n);for (i = 1; i <= n; i++) {sum += i;}printf("1到%d的和为%d\n", n, sum);return 0;}```第二章课后习题答案2.1 编写一个C程序,输入一个整数n,计算并输出n的平方。
```c#include <stdio.h>int main() {int n;printf("请输入一个整数:");scanf("%d", &n);printf("%d的平方为%d\n", n, n * n);return 0;}```2.2 编写一个C程序,输入一个整数n,判断并输出n是奇数还是偶数。
C语言程序设计现代方法第二版习题答案CProgrammingAModernApproach_new

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语言程序设计(第2版)》课后习题参考答案prt

《C语言程序设计》(邱晓红主编)课后习题参考答案第1章C语言及程序设计概述1.单选题(1)A (2)B (3)A (4)B (5)C2.填空题(1)//,/*…*/(2)scanf()(3)printf()3.判断题(1)对(2)错(3)错(4)对1.4简答题①概述C语言和C语言程序的主要特点。
答:1.C语言是高级语言。
它把高级语言的基本结构和语句与低级语言的实用性结合起来。
2。
C语言是结构式语言。
结构式语言的显著特点是代码及数据的分隔化,即程序的各个部分除了必要的信息交流外彼此独立。
这种结构化方式可使程序层次清晰,便于使用、维护以及调试。
①C语言功能齐全。
具有各种各样的数据类型,并引入了指针概念,可使程序效率更高。
②C语言适用范围大。
适合于多种操作系统,如Windows、DOS、UNIX、LINUX等等;也适用于多种机型。
②请编程,在计算机屏幕上显示:“您好,欢迎进入C语言世界!”解:#include<stdio.h>void main(){printf("您好,欢迎进入c预言世界!");}第二章:数据类型运算符与表达式1.单选题(1)C (2)D (3)C (4)B (5)C (6)A (7)B (8)D (9)A (10)B(11)C (12)C (13)D (14)A (15)B (16)C (17)A (18)A (19)B (20)C (21)C (22)D (23)C (24)A (25)D (26)B (27)C (28)B (29)B (30)A 2.填空题(1)sqrt(pow(y,x)+log10(y)) (2)36(3)6 (4)3 3(5)6 (6)36(7)int x=8,y=8; (8)1(9)E (10)7,9,6,8)(11)6 (12)66,96(13)240 (14)1,1,-1,-1(15)5,2,6 (16)1(17)!(18)2(19)(a>0&&a<101)&&(a%3==0||a%7==0)(20)A3.程序分析题(1)2 7 (VC++环境下,其它编译环境可能有不一样的结果)2 74 94 412 12(2)3 1 4 01 -616(3)100 d 68 D97 a 49 1(4)0 1 0 1(5)2 4 6 7-0.5800000 7.00000046.5800007.500000(6)33 12 113 13 082 32(7)618 30181(8)1 1 0 04.改错题(1)①无初始赋值,不能输出②数据精度丢失③少“;”号④单字符变量不能保存字符串常量⑤不能连续初始化⑥非法标识符(2)short i=38000溢出PI=3.1416 常量不能修改值Printf(“%d”,x%y) %必须是整数a*=(b+c)/=d复合赋值左边不能是表达式5、(1)#include <stdio.h>int main(){int H;float v,L1,L2,L,T,s1,M;printf("请输入开始里程数,单位为千米:\n");scanf("%f",&L1);printf("请输入结束里程数,单位为千米:\n");scanf("%f",&L2);printf("请输入时间,格式为时,分,秒\n");scanf("%d,%f,%f",&H,&M,&s1);T=H+M/60.0+s1/3600.0;//将时间折算成小时;L=L2-L1;//计算出这段时间走的路程,以千米计;v=L/T;printf("%f\n",v);return 0;}(2)#include <stdio.h>#define PI 3.14int main(){double r=2.5,h=5,V;V=(PI*r*r*h)/3;printf("%f\n",V);return 0;}第三章:算法概念与顺序结构程序设计1.选择题(1)D (2)D (3)D (4)B (5)C (6)A (在16位机答案为D)(7)B (8)C (9)B (10)D2.填空题.(1)一条语句;(2)小于左右(3)%%(4)输出项列表输出控制符(5)取地址取a的地址(6)从盘获取一个字符(7)大括号(8)f=68.000000(9)n1=%d\n n2=%d(10)7,5,c=33.程序分析题.(1)i=100,c=a,f=1.234000(2)i=65535,j=65536(10)1234,123.5,12345.53.4 编程题①编写一个程序,交换两个数的值。
C语言程序设计(第二版)习题参考答案

习题1
一、判断题
1.在计算机中,小数点和正负号都有专用部件来保存和表示。
2.二进制是由 0 和 1 两个数字组成的进制方式。
3.二进制数的逻辑运算是按位进行的,位与位之间没有进位和借位的关系。
4.在整数的二进制表示方法中,0 的原码、反码都有两种形式。
5.有符号数有三种表示法:原码、反码和补码。
6.设 c 为字符型变量值为‘A’,a 为整型变量值为 97,执行语句“putchar(c);putchar(a);”
后,输出结果为( )。
A.Aa
B.A97
C.A9
D.aA
7.已知字母 A 的 ASCII 码值为 65,以下语句段的输出结果是( )。
char c1='A',c2='Y'; printf("%d,%d\n",c1,c2);
A. X∧Y=1000 B. X∨Y=1111 C. X⊕Y=0011 D. ¯Y =1000
5.下列叙述中正确的是( )。
A.高级语言就是机器语言
B.汇编语言程序、高级语言程序都是计算机程序,但只有机器语言程序才是计算
机可以直接识别并执行的程序
C.C 语言因为具有汇编语言的一些特性,所以是汇编语言的一种
解:#include<stdio.h>
void main()
{ float a,b,x;
printf("请输入 a、b:\n");
scanf("%f %f",&a,&b);
x=-a/b;
printf("x=%f\n",x);
}
*5.仿照例 1.2 编程,输入圆柱体的半径和高,计算并输出圆柱体的体积。 解:#include <stdio.h>
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程序是由若干个函数构成的,其中有且只能有一个___函数。
C语言程序设计现代方法第二版,第八章课后编程习题全部答案

C语言程序设计现代方法第二版,第八章课后编程习题全部答案••50no2018-07-18自己练习时手写,难免会有些疏忽遗漏等各种各样问题,错误之处还请指出但这些代码确实已通过编译,实现了书上的输出结果,还希望能给需要之人作为个小参考8_11.#include <stdio.h>2.#include <stdbool.h>3.4.int main (void)5.{6.bool digit_seen[10] = {false}, digit_wr[10] = {false}, flag = false;7.int digit;8.long n;9.10.printf ('Enter a number: ');11.scanf ('%ld', &n);12.13.while (n > 0) {14.digit = n % 10;15.if (digit_seen[digit] == true) {16.flag = true;17.digit_wr[digit] = true;18.}19.digit_seen[digit] = true;20.n /= 10;21.}22.23.if (flag) {24.printf ('Repeated digits(s): ');25.for (int i = 0; i < 10; i ) {26.if (digit_wr[i]) printf ('%d ', i);27.}28.}29.else30.printf ('No repeated digit\n');31.32.return 0;33.}8_21.#define _CRT_SECURE_NO_WARNINGS2.3.#include <stdio.h>4.#include <stdlib.h>5.6.int main (void)7.{8.int digit_wr[10] = {0};9.int digit;10.int n;11.12.printf ('Enter a number:');13.scanf ('%d', &n);14.15.while (n > 0) {16.digit = n % 10;17.digit_wr[digit] ;18.n /= 10;19.}20.21.printf ('Digit:\t\t');22.for (int i = 0; i < 10; i ) {23.printf ('%3d', i);24.}25.26.printf ('\nOccurrences:\t');27.for (int i = 0; i < 10; i ) {28.printf ('%3d', digit_wr[i]);29.}30.31.printf('\n');32.system('pause');33.return 0;34.}8_31.#include <stdio.h>2.#include <stdbool.h>3.4./* * * * * * * * * * * * * * * * * * * * * * * *5.* 连续输入一百以内数,当输入的数小于或等于0 *6.* 时程序终止。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Chapter 2An swers to Selected Exercises2. [was #2] (a) The program contains one directive (#inelude) and four statements (three calls of printf and one return).(b)Parkinson's Law:Work expands so as to fill the timeavailable for its completi on.3. [was #4]#i nclude <stdio.h>int main(v oid){int height = 8, le ngth = 12, width = 10, volume;volume = height * len gth * width;printf("Dimensions: %dx%dx%d\n", length, width, height);prin tf("Volume (cubic in ches): %d\n", volume);printf("Dimensional weight (pounds): %d\n", (volume + 165) / 166);return 0;}4. [was #6] Here's one possible program:#i nclude <stdio.h>int main(v oid){int i, j, k;float x, y, z;prin tf("Value of i: %d\n", i);prin tf("Value of j: %d\n", j);prin tf("Value of k: %d\n", k);prin tf("Value of x: %g\n", x);prin tf("Value of y: %g\n", y);printf("Value of z: %g\n", z);return 0;}Whe n compiled using GCC and the n executed, this program produced the follow ing 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 chanee that you'll get exactly these nu mbers is small.5. [was #10] (a) is not legal because 100_bottles beg ins with a digit.8. [was #12] There are 14 tokens: a, =, (, 3, *, q, -, p, *, p, ), /, 3,and ;.An swers to Selected Programmi ng Projects4. [was #8; modified]#i nclude <stdio.h>int main(v oid){float orig in al_am ount, amoun t_with_tax;prin tf("E nter an amoun t:");sca nf("%f", &orig in al_am oun t);amoun t_with_tax = orig in al_am ount * 1.05f;prin tf("With tax added: $%.2f\n", amou nt_with_tax);return 0;}The amount_with_tax variable is unnecessary. If we remove it, the programis slightly shorter: #i nclude <stdio.h>时磊诫呎…}int main(v oid){float orig in al_am ount;prin tf("E nter an amoun t:");sea nf("%f", &orig in al_am oun t);printf("With tax added: $%.2f\n", original_amount * 1.05f);return 0;}Chapter 3An swers to Selected Exercises2. [was #2](a) printf(%8.1e", x);(b) printf("%10.6e", x);(e) pri ntf("%-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,An swers to Selected Programmi ng Projects1. [was #4; modified]#i nclude <stdio.h>int main(v oid){int mon th, day, year;prin tf("E nter a date (mm/dd/yyyy):");sca nf("%d/%d/%d", &mon th, & day, &year);prin tf("You en tered the date %d%.2d%.2d\n", year, mon th, day);return 0;3. [was #6; modified]respectively.时Sr忖呎#i nclude <stdio.h> int main(v oid){int prefix, group, publisher, item, check_digit;printf("Enter ISBN:");sca nf("%d-%d-%d-%d-%d", & prefix, & group, & publisher, & tem, &check_digit);prin tf("GS1 prefix: %d\n", prefix);prin tf("Group ide ntifier: %d\n", group);prin tf("Publisher code: %d\n", publisher);printf("Item number: %d\n", item);prin tf("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 4An swers 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 0------------------- 时磊忖呎…... ..... ... ...13. [was #8] The expressi on ++i is equivale nt to (i += 1). The value of both expressi ons is i after the in creme nt has bee n performed.An swers to Selected Programmi ng Projects2. [was #4]#i nclude <stdio.h>int main(v oid){int n;prin tf("E nter a three-digit nu mber:");sca nf("%d", &n);printf("The reversal is: %d%d%d\n", n % 10, (n / 10) % 10, n / 100);return 0;}Chapter 5An swers 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 ison etwosince there are no break stateme nts after the cases.An swers to Selected Programmi ng Projects 2. [was #6]时Sr忖呎#i nclude <stdio.h> int main(v oid){int hours, minu tes;prin tf("E nter a 24-hour time:"); sca nf("%d:%d", & hours, &min utes);prin tf("Equivale nt 12-hour time:");if (hours == 0)printf("12:%.2d AM\n", minutes);else if (hours < 12)prin tf("%d:%.2d AM\n", hours, mi nutes); else if (hours == 12)prin tf("%d:%.2d PM\n", hours, mi nutes); elseprin tf("%d:%.2d PM\n", hours - 12, minu tes);return 0;}4. [was #8; modified]#i nclude <stdio.h> int main(v oid){int speed;prin tf("E nter a wi nd speed in kno ts:"); scanf("%d", &speed);if (speed < 1)prin tf("Calm\n"); else if (speed <= 3)prin tf("Light air\n"); else if (speed <= 27)prin tf("Breeze\n"); else if (speed <= 47)prin tf("Gale\n"); else if (speed <= 63)prin tf("Storm\n"); else------------------- 时磊忖呎…... ..... ... ...prin tf("Hurrica ne\n");return 0;}6. [was #10]#i nclude <stdio.h>int main(v oid){in t check_digit, d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5,first_sum, sec on d_sum, total;prin tf("E nter the first (sin gle) digit:");scanf("%1d", &d);prin tf("E nter first group of five digits:");scanf("%1d%1d%1d%1d%1d", &i1, &i2, &3, &i4, &i5);prin tf("E nter sec ond group of five digits:");scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5);prin tf("E nter the last (sin gle) digit:");sca nf("%1d", & check_digit);first_sum = d + i2 + i4 + j1 + j3 + j5;sec on d_sum = i1 + i3 + i5 + j2 + j4;total = 3 * first_sum + sec on d_sum;if (check_digit == 9 - ((total - 1) % 10))prin tf("VALID\n");elseprin tf("NOT VALID\n");return 0;}10. [was #14]#i nclude <stdio.h>int main(v oid){int grade;prin tf("E nter nu merical grade:");scanf("%d", &grade);时磊忖呎…if (grade < 0 || grade > 100) {printf("lllegal grade'n");return 0;}switch (grade / 10) {case 10:case 9: prin tf("Letter grade: A\n");break;case 8: prin tf("Letter grade: B\n");break;case 7: prin tf("Letter grade: C\n");break;case 6: prin tf("Letter grade: D\n");break;case 5:case 4:case 3:case 2:case 1:case 0: prin tf("Letter grade: F\n");break;}return 0;}Chapter 6An swers to Selected Exercises 4. [was #10] (c) is not equivale nt to (a) and (b), because i is in creme nted before the loop body is executed.10. [was #12] Co nsider the followi ng while loop:while (…){con ti nue;}The equivale nt code using goto would have the follow ing appeara nee:------------------- 时磊忖呎…... ..... ... ... while (…){goto loop_e nd;loop_e nd: ; /* n ull stateme nt */} _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);elseprin tf("%d is prime\n", n);14. [was #16] The problem is the semicoIon at the end of the first line.If we remove it, the statement is now correct:if (n % 2 == 0)printf("n is eve n\n");An swers to Selected Programmi ng Projects2. [was #2]#i nclude <stdio.h>int main(v oid){int m, n, rema in der;prin tf("E nter two in tegers:");sca nf("%d%d", &m, &n);while (n != 0) {rema in der = m % n;m = n;n = rema in der;}时磊忖呎…prin tf("Greatest com mon divisor: %d\n", m);return 0;}4. [was #4]#i nclude <stdio.h>int main(v oid){float commissi on, value;prin tf("E nter value of trade:");sca nf("%f", &value);while (value != 0.0f) {if (value < 2500.00f)commissio n = 30.00f + .017f * value;else if (value < 6250.00f)commission = 56.00f + .0066f * value;else if (value < 20000.00f)commissio n = 76.00f + .0034f * value;else if (value < 50000.00f)commissio n = 100.00f + .0022f * value;else if (value < 500000.00f)commissio n = 155.00f + .0011f * value;elsecommissio n = 255.00f + .0009f * value;if (commissio n < 39.00f)commissi on = 39.00f;prin tf("Commissio n: $%.2f\n\n", commissio n);prin tf("E nter value of trade:");scan f("%f", &value);}return 0;}6. [was #6] #i nclude <stdio.h> int main (void) {int i, n;时磊忖呎…prin tf("E nter limit on maximum square:"); sea nf("%d", &n);for (i = 2; i * i <= n; i += 2) prin tf("%d\n", i * i);return 0;}8. [was #8]#i nclude <stdio.h> int main(v oid){int i, n, start_day;prin tf("E nter nu mber of days in mon th:");sea nf("%d", &n);printf("Enter starting day of the week (1=Sun, 7=Sat):"); sea nf("%d", &start_day);/* print any leadi ng "bla nk dates" */ for (i = 1; i < start_day; i++)prin tf("");/* now print the cale ndar */ for (i = 1; i <= n; i++) {prin tf("%3d", i);if ((start_day + i - 1) % 7 == 0) prin tf("\n");}return 0;}Chapter 7An swers to Selected Exercises裁磊诫呎3. [was #4] (b) is not legal.4. [was #6] (d) is illegal, since printf requires a string, not a character, as its first argume nt.10. [was #14] unsigned int, because the (int) cast applies only to j, not j * k.12. [was #16] The value of i is conv erted to float and added to f, the nthe result is con verted 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.An swers to Selected Programmi ng 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]#i nclude <stdio.h>int main(v oid){int i, n;char ch;prin tf("This program prints a table of squares.\n");prin tf("E nter nu mber of en tries in table:");sca nf("%d", &n);ch = getchar();/* dispose of n ew-l ine character follow ing nu mber of en tries *//* could simply be getchar(); */for (i = 1; i <= n; i++) {prin tf("%10d%10d\n", i, i * i);if (i % 24 == 0) {prin tf("Press En ter to continu e...");ch = getchar(); /* or simply getchar(); */}}return 0;5. [was #10]#in elude <ctype.h>#i nclude <stdio.h>int main(v oid){int sum = 0;char ch;prin tf("E nter 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]#i nclude <stdio.h>int main(v oid){prin tf("Size of int: %d\n", (int) sizeof(i nt));prin tf("Size of short: %d\n", (int) sizeof(short));prin tf("Size of long: %d\n", (int) sizeof(l on g));prin tf("Size of float: %d\n", (int) sizeof(float));prin tf("Size of double: %d\n", (int) sizeof(double));prin tf("Size of long double: %d\n", (int) sizeof(l ong double));return 0;}Since the type of a sizeof expressi on may vary from one impleme ntati on to ano ther, it's n ecessary in C89 to cast sizeof expressi ons 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 conv ersi on specificatio n.Chapter 8An swers to Selected Exercises1. [was #4] The problem with sizeof(a) / sizeof( t) is that it can't easily be checked for correct ness by some one readi ng the program. (The readerwould have to locate the declaration of a and makesure that its elements have type t.)2. [was #8] To use a digit d (in character form) as a subscript into thearray a, we would write a[d-'0']. This assumes that digits haveconsecutive codes in the underlying character set, which is true of ASCII and other popular character sets.7. [was #10]const int segme nts[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}};An swers to Selected Programmi ng Projects2. [was #2]#i nclude <stdio.h>int main(v oid){int digit_cou nt[1O] = {0};int digit;long n;prin tf("E nter a nu mber:");sca nf("%ld", &n);while (n > 0) {digit = n % 10;digit_co un t[digit]++;n /= 10;}printf ("Digit:");for (digit = 0; digit <= 9; digit++)prin tf("%3d", digit);prin tf("\nO ccurre nces:");for (digit = 0; digit <= 9; digit++)prin tf("%3d", digit_cou nt[digit]);prin tf("\n");return 0;}5. [was #6]#i nclude <stdio.h>#define NUM_RATES ((int) (sizeof(value) / sizeof(value[0]))) #defi ne INITIAL_BALANCE 100.00int main(v oid){int i, low_rate, mon th, nu m_years, year;double value[5];printf("Enter interest rate:");scanf("%d", &low_rate);prin tf("E nter nu mber of years:");sea nf("%d", &nu m_years);prin tf("\nYears");for (i = 0; i < NUM_RATES; i++) {prin tf("%6d%%", low_rate + i);value[i] = INITIAL_BALANCE;}prin tf("\n");for (year = 1; year <= nu m_years; year++) {prin tf("%3d ", year);for (i = 0; i < NUM_RATES; i++) {for (month = 1; month <= 12; mon th++)value[i] += ((double) (low_rate + i) / 12) / 100.0 * value[i];prin tf("%7.2f", value[i]);}prin tf("\n");}return 0;}8. [was #12]#i nclude <stdio.h>#defi ne NUM_QUIZZES 5#defi ne NUM_STUDENTS 5int main(v oid){in t grades[NUM_STUDENTS][NUM_QUIZZES];int high, low, quiz, stude nt, total;for (student = 0; student < NUM_STUDENTS; student++) {prin tf("E nter grades for stude nt %d: ", stude nt + 1);for (quiz = 0; quiz < NUM_QUIZZES; quiz++)scan f("%d", & grades[stude nt][quiz]);}prin tf("\nStude nt Total Average\n");for (student = 0; student < NUM_STUDENTS; student++) {prin tf("%4d ", stude nt + 1);total = 0;for (quiz = 0; quiz < NUM_QUIZZES; quiz++) total += grades[stude nt][quiz];printf("%3d %3d\n", total, total / NUM_QUIZZES);}prin tf("\nQuiz Average High Low\n");for (quiz = 0; quiz < NUM_QUIZZES; quiz++) {prin tf("%3d ", quiz + 1);total = 0;high = 0;low = 100;for (stude nt = 0; stude nt < NUM_STUDENTS; stude nt++) { total += grades[stude nt][quiz];if (grades[stude nt][quiz] > high)high = grades[stude nt][quiz];if (grades[stude nt][quiz] < low)low = grades[stude nt][quiz];}prin tf("%3d %3d %3d\n", total / NUM_STUDENTS, high, low);}return 0;}Chapter 9An swers to Selected Exercises2. [was #2]int check(i nt x, int y, int n){return (x >= 0 && x <= n - 1 && y >= 0 && y <= n - 1);}4. [was #4]int day_of_year(i nt mon th, int day, int year){int num_days[] = {31,28, 31,30, 31,30, 31,31,30, 31, 30, 31};int day_c ount = 0, i;for (i = 1; i < mon th; i++)day_co unt += nu m_days[i-1];/* adjust for leap years, assu ming they are divisible by 4 */if (year % 4 == 0 && mon th > 2)day_co un t++;retur n day_co unt + 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(i nt 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 itdoes n't specify the type of the parameter. (d) in correctly specifies that f returns an int value in C89; in C99, omitting the return type is illegal.10. [was #10](a)int largest(i nt 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© nt a[], int n){int i, avg = 0;for (i = 0; i < n; i++)avg += a[i];retur n avg / n;}(c)int nu m_positive(i nt a[], int n){ _int i, count = 0;for (i = 0; i < n; i++) if (a[i] > 0) coun t++;retur n count;}15. [was #12; modified]double media n( 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;}retur n result; } 17. [was #14]------------------- 时需5说int fact(i nt 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: #i nclude <stdio.h>void pb(i nt n);int main(v oid){int n;prin tf("E nter a nu mber:");sca nf("%d", &n);prin tf("Output of pb:");pb( n);prin tf("\n");return 0;}void pb(i nt n){if (n != 0) {pb(n / 2);putchar('0' + n % 2);}}pb prints the binary represe ntati on of the argume nt n, assu ming that n is greatercodes in than 0. (We also assume that digits have consecutivethe un derly ing character set.) For example:En ter a nu mber: 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 callspb(13), which finds that 13 is not equal to 0, so it callspb(6), which finds that 6 is not equal to 0, so it calls pb(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 retur ns, caus ingpb(1) to print 1 and retur n, caus ing pb(3) to print 1and retur n, caus ingpb(6) to print 0 and retur n, caus ingpb(13) to print 1 and retur n, caus ingpb(26) to print 0 and retur n, caus ingpb(53) to print 1 and retur n.Chapter 10An swers 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.An swers to Selected Programmi ng Projects3. [was #4]#in clude <stdbool.h> /* C99 only */#i nclude <stdio.h>#i nclude <stdlib.h>#defi ne NUM_CARDS 5#defi ne RANK 0#defi ne SUIT 1/* exter nal variables */in t han d[NUM_CARDS][2];/* 0 1*/ bool straight, flush, four, three; int pairs; /* can be 0, 1, or 2 */ /* prototypes */ void read_cards(void); void an alyze_ha nd(void);void prin t_result(void);/*********************************************************** main: Calls read_cards, an alyze_ha nd, and prin t_result* repeatedly. ***********************************************************/int main(v oid){for (;;) {read_cards();an alyze_ha nd();prin t_result();} _} /*********************************************************** read_cards: Reads the cards into the external variable* hand; checks for bad cards and duplicate ** cards. ***********************************************************/void read_cards(void){char ch, ran k_ch, suit_ch;int i, ra nk, suit;bool bad_card, duplicate_card;int cards_read = 0;while (cards_read < NUM_CARDS) { bad_card = false;prin tf("E nter a card:");ran k_ch = getchar();switch (ran k_ch) {case 'O': 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) {prin tf("Bad card; igno red.\n");con ti nue;}duplicate_card = false;for (i = 0; i < cards_read; i++)if (ha nd[i][RANK] == rank && han d[i][SUIT] == suit) {prin tf("Duplicate card; igno red.\n");duplicate_card = true;break;}if (!duplicate_card) {ha nd[cards_read][RANK] = rank; ha nd[cards_read][SUIT] = suit;cards_read++;} _}} /*********************************************************** an alyze_ha nd: Determ ines whether the hand contains a* straight, a flush, four-of-a-k ind, ** an d/or three-of-a-k ind; determ ines the ** nu mber of pairs; stores the results into ** the exter nal variables straight, flush, ** four, three, and pairs. ***********************************************************/void an alyze_ha nd(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 = han d[card][RANK];suit = han d[card][SUIT];if (ha nd[card+1][RANK] < rank) {han d[card][RANK] = ha nd[card+1][RANK];han d[card][SUIT] = ha nd[card+1][SUIT];han d[card+1][RANK] = rank;han d[card+1][SUIT] = suit;}}/* check for flush */ suit = han d[0][SUIT];for (card = 1; card < NUM_CARDS; card++) if (ha nd[card][SUIT] != suit) flush = false;/* check for straight */for (card = 0; card < NUM_CARDS - 1; card++)if (ha nd[card][RANK] + 1 != han d[card+1][RANK])straight = false;/* check for 4-of-a-k ind, 3-of-a-k ind, and pairs bylook ing for "r uns" of cards with ide ntical ranks */card = 0;while (card < NUM_CARDS) {rank = han d[card][RANK];run = 0;do {run++;card++;} while (card < NUM_CARDS && han d[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 exter nal* variables straight, flush, four, three, ** and pairs. *********************************************************void prin t_result(void){ _if (straight && flush) pri ntf("Straight flush");else if (four) prin tf("Four of a ki nd");else if (three &&pairs == 1) prin tf("Full house");prin tf("Flush");prin tf("Straight");prin tf("Three of a ki nd");else if (pairs == 2) prin tf("Two pairs");else if (pairs == 1) prin tf("Pair");else if (flush) else if (straight) else if (three)--------- 时器Sr亦..... . .... ... ...printf("High card");elseprin tf("\n\n");}5. [was #6]#in clude <stdbool.h> /* C99 only */#i nclude <stdio.h>#i nclude <stdlib.h> #defi ne NUM_RANKS 13#defi ne NUM_SUITS 4#defi ne NUM_CARDS 5/* exter nal variables */int num _in_ra nk[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 an alyze_ha nd(void);void prin t_result(void);/*********************************************************** main: Calls read_cards, an alyze_ha nd, and prin t_result* repeatedly. ***********************************************************/ int main(v oid){for (;;) {read_cards();an alyze_ha nd();prin t_result();} _}/*********************************************************** read_cards: Reads the cards into the exter nal* variables num_in_rank and num_in _suit;* checks for bad cards and duplicate cards.**********************************************************------------------- 时磊5说----- - ---- -------void read_cards(void){ _bool card_exists[NUM_RANKS][NUM_SUITS];char ch, ran k_ch, suit_ch;int rank, suit;bool bad_card;int cards_read = 0;for (ra nk = 0; rank < NUM_RANKS; ran k++) { num_in_ran k[ra nk] = 0;for (suit = 0; suit < NUM_SUITS; suit++)card_exists[ra nk][suit] = false;} _for (suit = 0; suit < NUM_SUITS; suit++)num_in _suit[suit] = 0;while (cards_read < NUM_CARDS) {bad_card = false;prin tf("E nter a card:");ran k_ch = getchar();switch (ran k_ch) {case 'O': 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;。