数据结构与程序设计C描述Kruse着高等教育出版社课后答案
《数据结构与程序设计C描述Kruse着高等教育出版社课后答案》由会员分享,可在线阅读,更多相关《数据结构与程序设计C描述Kruse着高等教育出版社课后答案(800页珍藏版)》请在装配图网上搜索。
1、ProgrammingPrinciples 11.2 THE GAME OF LIFEExercises 1.2Determine by hand calculation what will happen to each of the configurations shown in Figure 1.1 overthe course of five generations. Suggestion: Set up the Life configuration on a checkerboard. Use onecolor of checkers for living cells in the c
2、urrent generation and a second color to mark those that will beborn or die in the next generation.Answer(a)Figure remains stable.(b)(c)(d)Figure is stable.12 Chapter 1 _ Programming Principles(e)(f)Figure repeats itself.(g)(h)(i)Figure repeats itself.(j)(k)(l)Figure repeats itself.Section 1.3 _ Prog
3、ramming Style 31.3 PROGRAMMING STYLEExercises 1.3E1. What classes would you define in implementing the following projects? What methods would your classespossess?(a) A program to store telephone numbers.Answer The program could use classes called Phone_book and Person. The methods for a Phone_bookob
4、ject would include look_up_name, add_person, remove_person. The methods for a Personobject would include Look_up_number. Additional methods to initialize and print objects ofboth classes would also be useful.(b) A program to play Monopoly.Answer The program could use classes called Game_board, Prope
5、rty, Bank, Player, and Dice. In additionto initialization and printing methods for all classes, the following methods would be useful. Theclass Game_board needs methods next_card and operate_jail. The class Property needs methodschange_owner, look_up_owner, rent, build, mortgage, and unmortgage. The
6、 class Bank needsmethods pay and collect. The class Player needs methods roll_dice, move_location, buy_propertyand pay_rent. The class Dice needs a method roll.(c) A program to play tic-tac-toe.Answer The program could use classes called Game_board and Square. The classes need initializationand prin
7、ting methods. The class Game_board would also need methods make_move andis_game_over. The class Square would need methods is_occupied, occupied_by, and occupy.(d) A program to model the build up of queues of cars waiting at a busy intersection with a traffic light.Answer The program could use classe
8、s Car, Traffic_light, and Queue. The classes would all need initializationand printing methods. The class Traffic_light would need additional methods change_statusand status. The class Queue would need additional methods add_car and remove_car.E2. Rewrite the following class definition, which is sup
9、posed to model a deck of playing cards, so that itconforms to our principles of style.class a / a deck of cardsint X; thing Y152; /* X is the location of the top card in the deck. Y1 lists the cards. */ public:a( );void Shuffle( ); / Shuffle randomly arranges the cards.thing d( ); / deals the top ca
10、rd off the deck;Answerclass Card_deck Card deck52;int top_card;public:Card_deck( );void Shuffle( );Card deal( );4 Chapter 1 _ Programming PrinciplesE3. Given the declarationsint ann, i, j;where n is a constant, determine what the following statement does, and rewrite the statement to accomplishthe s
11、ame effect in a less tricky way.for (i = 0; i < n; i.)for (j = 0; j < n; j.)aij = (i . 1)/(j . 1) * (j . 1)/(i . 1);Answer This statement initializes the array a with all 0s except for 1s down the main diagonal. A lesstricky way to accomplish this initialization is:for (i = 0; i < n; i.)for
12、 (j = 0; j < n; j.)if (i = j) aij = 1;else aij = 0;E4. Rewrite the following function so that it accomplishes the same result in a less tricky way.void does_something(int &first, int &second)first = second first;second = second first;first = second . first;Answer The function interchanges
13、 the values of its parameters:void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */int temp = first;first = second;second = temp;E5. Determine what each of the following functions does. Rewrit
14、e each function with meaningful variablenames, with better format, and without unnecessary variables and statements.(a) int calculate(int apple, int orange) int peach, lemon;peach = 0; lemon = 0; if (apple < orange)peach = orange; else if (orange <= apple)peach = apple; else peach = 17;lemon =
15、 19; return(peach);Answer The function calculate returns the larger of its two parameters.int larger(int a, int b)/* Pre: The integers a and b have been initialized.Post: The value of the larger of a and b is returned. */if (a < b) return b;return a;Section 1.3 _ Programming Style 5(b) For this p
16、art assume the declaration typedef float vectormax;float figure (vector vector1) int loop1, loop4; float loop2, loop3;loop1 = 0; loop2 = vector1loop1; loop3 = 0.0;loop4 = loop1; for (loop4 = 0;loop4 < max; loop4.) loop1 = loop1 . 1;loop2 = vector1loop1 1;loop3 = loop2 . loop3; loop1 = loop1 1;loo
17、p2 = loop1 . 1;return(loop2 = loop3/loop2); Answer The function figure obtains the mean of an array of floating point numbers.float mean(vector v)/* Pre: The vector v contains max floating point values.Post: The mean of the values in v is returned. */float total = 0.0;for (int i = 0; i < max; i.)
18、total += vi;return total/(float) max);(c) int question(int &a17, int &stuff) int another, yetanother, stillonemore;another = yetanother; stillonemore = a17;yetanother = stuff; another = stillonemore;a17 = yetanother; stillonemore = yetanother;stuff = another; another = yetanother;yetanother
19、= stuff; Answer The function question interchanges the values of its parameters.void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */int temp = first;first = second;second = temp;(d) int myste
20、ry(int apple, int orange, int peach) if (apple > orange) if (apple > peach) if(peach > orange) return(peach); else if (apple < orange)return(apple); else return(orange); else return(apple); elseif (peach > apple) if (peach > orange) return(orange); elsereturn(peach); else return(ap
21、ple); Answer The function mystery returns the middle value of its three parameters.6 Chapter 1 _ Programming Principlesint median(int a, int b, int c)/* Pre: None.Post: Returns the middle value of the three integers a, b, c. */if (a > b)if (c > a) return a; / c > a > belse if (c > b)
22、return c; / a >= c > belse return b; / a > b >= celseif (c > b) return b; / c > b >= aelse if (c > a) return c; / b >= c > aelse return a; / b >= a >= cE6. The following statement is designed to check the relative sizes of three integers, which you may assumeto be
23、 different from each other:if (x < z) if (x < y) if (y < z) c = 1; else c = 2; elseif (y < z) c = 3; else c = 4; else if (x < y)if (x < z) c = 5; else c = 6; else if (y < z) c = 7; elseif (z < x) if (z < y) c = 8; else c = 9; else c = 10;(a) Rewrite this statement in a for
24、m that is easier to read.Answerif (x < z)if (x < y) / x < z and x < yif (y < z) c = 1; / x < y < zelse c = 2; / x < z <= yelse / y <= x < zif (y < z) c = 3; / y <= x < zelse c = 4; / impossibleelse / z <= xif (x < y) / z <= x < yif (x < z) c =
25、 5; / impossibleelse c = 6; / z <= x < yelse / z <= x and y <= xif (y < z) c = 7; / y < z <= x/ z <= y <= xif (z < x) / z <= y <= x, z < xif (z < y) c = 8; / z < y <= xelse c = 9; / z = y < x, impossibleelse c = 10; / y <= z = x, impossible(b) Si
26、nce there are only six possible orderings for the three integers, only six of the ten cases can actuallyoccur. Find those that can never occur, and eliminate the redundant checks.Answer The impossible cases are shown in the remarks for the preceding program segment. After theirremoval we have:if (x
27、< z)if (x < y) / x < z and x < yif (y < z) c = 1; / x < y < zelse c = 2; / x < z <= yelse c = 3; / y <= x < zelse / z <= xif (x < y) c = 6; / z <= x < yelse / z <= x and y <= xif (y < z) c = 7; / y < z <= xelse c = 8; / z <= y <= xSec
28、tion 1.3 _ Programming Style 7(c) Write a simpler, shorter statement that accomplishes the same result.Answerif (x < y) && (y < z) c = 1;else if (x < z) && (z < y) c = 2;else if (y < x) && (x < z) c = 3;else if (z < x) && (x < y) c = 6;else if
29、(y < z) && (z < x) c = 7;else c = 8;E7. The following C+ function calculates the cube root of a floating-point number (by the Newton approximation),using the fact that, if y is one approximation to the cube root of x, thenz . 2y . x=y23cube roots is a closer approximation.float functio
30、n fcn(float stuff) float april, tim, tiny, shadow, tom, tam, square; int flag;tim = stuff; tam = stuff; tiny = 0.00001;if (stuff != 0) do shadow = tim . tim; square = tim * tim;tom = (shadow . stuff/square); april = tom/3.0;if (april*april * april tam > tiny) if (april*april*april tam< tiny) f
31、lag = 1; else flag = 0; else flag = 0;if (flag = 0) tim = april; else tim = tam; while (flag != 1);if (stuff = 0) return(stuff); else return(april); (a) Rewrite this function with meaningful variable names, without the extra variables that contribute nothingto the understanding, with a better layout
32、, and without the redundant and useless statements.Answer After some study it can be seen that both stuff and tam play the role of the quantity x in theformula, tim plays the role of y, and tom and april both play the role of z. The object tiny is asmall constant which serves as a tolerance to stop
33、the loop. The variable shadow is nothing but2y and square is y2 . The complicated two-line if statement checks whether the absolute valuejz3 xj is less than the tolerance, and the boolean flag is used then only to terminate the loop.Changing all these variables to their mathematical forms and elimin
34、ating the redundant onesgives:const double tolerance = 0.00001;double cube_root(double x) / Find cube root of x by Newton methoddouble y, z;y = z = x;if (x != 0.0)do z = (y . y . x/(y * y)/3.0;y = z; while (z * z * z x > tolerance | x z * z * z > tolerance);return z;(b) Write a function for ca
35、lculating the cube root of x directly from the mathematical formula, by startingwith the assignment y = x and then repeatingy = (2 * y . (x/(y * y)/3until abs(y * y * y x) < 0.00001.8 Chapter 1 _ Programming PrinciplesAnswer const double tolerance = 0.00001;double formula(double x) / Find cube ro
36、ot of x directly from formuladouble y = x;if (x != 0.0)do y = (y . y . x/(y * y)/3.0; while (y * y * y x > tolerance | x y * y * y > tolerance);return y;(c) Which of these tasks is easier?Answer It is often easier to write a program fromscratch than it is to decipher and rewrite a poorly writt
37、enprogram.E8. The mean of a sequence of numbers is their sum divided by the count of numbers in the sequence. Thestatistics (population) variance of the sequence is the mean of the squares of all numbers in the sequence, minusthe square of the mean of the numbers in the sequence. The standard deviat
38、ion is the square root of thevariance. Write a well-structured C+ function to calculate the standard deviation of a sequence of nfloating-point numbers, where n is a constant and the numbers are in an array indexed from 0 to n1,which is a parameter to the function. Use, then write, subsidiary functi
39、ons to calculate the mean andvariance.Answer #include <math.h>double variance(double v, int n);double standard_deviation(double v, int n) / Standard deviation of vreturn sqrt(variance(v, n);This function uses a subsidiary function to calculate the variance.double mean(double v, int n);double v
40、ariance(double v, int n)/ Find the variance for n numbers in vint i;double temp;double sum_squares = 0.;for (i = 0; i < n; i.)sum_squares += vi * vi;temp = mean(v, n);return sum_squares/n temp * temp;This function in turn requires another function to calculate the mean.double mean(double v, int n
41、) / Find the mean of an array of n numbersint i;double sum = 0.0;for (i = 0; i < n; i.)sum += vi;return sum/n;Section 1.3 _ Programming Style 9E9. Design a program that will plot a given set of points on a graph. The input to the program will be a textfile, each line of which contains two numbers
42、 that are the x and y coordinates of a point to be plotted.The program will use a function to plot one such pair of coordinates. The details of the function involveplotting the specificmethod of plotting and cannot be written since they depend on the requirements of the plottingequipment, which we d
43、o not know. Before plotting the points the program needs to know the maximumand minimum values of x and y that appear in its input file. The program should therefore use anotherfunction bounds that will read the whole file and determine these four maxima and minima. Afterward,another function is use
44、d to draw and label the axes; then the file can be reset and the individual pointsplotted.(a) Write the main program, not including the functions.Answer #include <fstream.h>#include "calls.h"#include "bounds.c"#include "draw.c"int main(int argc, char *argv)/ Read
45、coordinates from file and plot coordinate pairs.ifstream file(argv1);if (file = 0) cout << "Can not open input points file" << endl;cout << "Usage:nt plotter input_points " << endl;exit(1);double xmax, xmin; / bounds for x valuesdouble ymax, ymin; / bounds
46、 for y valuesdouble x, y; / x, y values to plotbounds(file, xmax, xmin, ymax, ymin);draw_axes(xmax, xmin, ymax, ymin);file.seekg(0, ios : beg); / reset to beginning of filewhile (!file.eof( ) file >> x >> y;plot(x, y);(b) Write the function bounds.Answer void bounds(ifstream &file, d
47、ouble &xmax, double &xmin,double &ymax, double &ymin)/ determine maximum and minimum values for x and ydouble x, y;file >> x >> y;xmax = xmin = x;ymax = ymin = y;while (!file.eof( ) file >> x >> y;if (x < xmin)xmin = x;if (x > xmax)xmax = x;if (y < ym
48、in)ymin = y;10 Chapter 1 _ Programming Principlesif (y > ymax)ymax = y;(c) Write the preconditions and postconditions for the remaining functions together with appropriate documentationshowing their purposes and their requirements.Answer void draw_axes(double xmax, double xmin,double ymax, double
49、 ymin)/* Pre: The parameters xmin, xmax, ymin, and xmax give bounds for the x and y co-ordinates.Post: Draws and labels axes according to the given bounds. */void plot(double x, double y)/* Pre: The parameters x and y give co-ordinates of a point.Post: The point is plotted to the ouput graph. */1.4
50、CODING, TESTING, AND FURTHER REFINEMENTExercises 1.4E1. If you suspected that the Life program contained errors, where would be a good place to insert scaffoldinginto the main program? What information should be printed out?Answer Since much of the programs work is done in neighbor_count, a good pla
51、ce would be withinthe loops of the update method, just before the switch statement. The values of row, col, andneighbor_count could be printed.E2. Take your solution to Section 1.3, Exercise E9 (designing a program to plot a set of points), and indicategood places to insert scaffolding if needed.Ans
52、wer Suitable places might be after draw_axes (printing its four parameters) and (with a very smalltest file to plot) after the call to plot (printing the coordinates of the point just plotted).E3. Find suitable black-box test data for each of the following:(a) A function that returns the largest of
53、its three parameters, which are floating-point numbers.Answereasy values: .1; 2; 3., .2; 3; 1., .3; 2; 1.typical values: .0; 0:5;9:6., .1:3; 3:5; 0:4., .2:1;3:5;1:6.extreme values: .0; 0; 0., .0; 1; 1., .1; 0; 1., .0; 0; 1.(b) A function that returns the square root of a floating-point number.Answer
54、easy values: 1, 4, 9, 16.typical values: 0.4836, 56.7, 9762.34.extreme value: 0.0.illegal values: 0.4353, 9.Section 1.4 _ Coding, Testing, and Further Refinement 11(c) A function that returns the least common multiple of its two parameters, which must be positive integers.(The least common multiple
55、is the smallest integer that is a multiple of both parameters. Examples:The least common multiple of 4 and 6 is 12, of 3 and 9 is 9, and of 5 and 7 is 35.)Answereasy values: .3; 4., .4; 8., .7; 3.typical values: .7; 8., .189; 433., .1081; 1173.illegal values: .7;6., .0; 5., .0; 0., .1;1.(d) A functi
56、on that sorts three integers, given as its parameters, into ascending order.Answereasy values: .5; 3; 2., .2; 3; 5., .3; 5; 2., .5; 2; 3., .1;2;3.extreme values: .1; 1; 1., .1; 2; 1., .1; 1; 2.typical values: .487;390; 20., .0; 589; 333.(e) A function that sorts an array a containing n integers inde
57、xed from 0 to n 1 into ascending order,where a and n are both parameters.Answer For the number n of entries to be sorted choose values such as 2, 3, 4 (easy values), 0, 1, maximumsize of a (extreme values), and 1 (illegal value). Test with all entries of a the same value, theentries already in ascen
58、ding order, the entries in descending order, and the entries in randomorder.E4. Find suitable glass-box test data for each of the following:(a) The statementif (a < b) if (c > d) x = 1; else if (c = d) x = 2;else x = 3; else if (a = b) x = 4; else if (c = d) x = 5;else x = 6;Answer Choose valu
59、es for a and b, such as .1; 2., .2; 1., and .1; 1., so that each of a < b, a > b, and a =b holds true. Choose three similar pairs of values for c and d, giving nine sets of test data.(b) The Life method neighbor_count(row, col).Answer Set row in turn to 1, maxrow, and any intermediate value, a
60、s well as 0 and maxrow . 1 (as illegalvalues). Choose col similarly. For each of the legal (row, col) pairs set up the Life object so thatthe number of living neighbors of (row, col) is each possible value between 0 and 8. Finally, makethe cell at (row, col) itself either living or dead. (This proce
61、ss gives 98 sets of test data, providedmaxrow and maxrow are each at least 3.)Programming Projects 1.4P1. Enter the Life program of this chapter on your computer and make sure that it works correctly.Answer The complete program is implemented in the life subdirectory for Chapter 1.#include "./.
62、/c/utility.h"#include "life.h"#include "././c/utility.cpp"#include "life.cpp"int main() / Program to play Conway's game of Life./*Pre: The user supplies an initial configuration of living cells.Post: The program prints a sequence of pictures showing the changes
63、 inthe configuration of living cells according to the rules forthe game of Life.Uses: The class Life and its methods initialize(), print(), andupdate(); the functions instructions(), user_says_yes().*/12 Chapter 1 _ Programming PrinciplesLife configuration;instructions();configuration.initialize();c
64、onfiguration.print();cout << "Continue viewing new generations? " << endl;while (user_says_yes() configuration.update();configuration.print();cout << "Continue viewing new generations? " << endl;const int maxrow = 20, maxcol = 60; / grid dimensionsclass Life public:void initialize();void print();void update();private:int gridmaxrow + 2maxcol + 2; / Allow two extra rows and columns.int neighbor_count(int row, int col);void Life:print()/*Pre: The Life object contains a configuration.Post
- 温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 四年级科学下册《食物包装上的信息》教科版课件
- 加强官德修养-做有德领导教学课件
- 医院药物临床试验机构资料管理员专项培训教材课件
- 北京中小学学生电子学籍管理系统一年级信息录入培训课件
- 医疗服务全面质量管理-课件
- 加强处方点评促进合理用药课件
- 加强学科建设打造品牌医院提升三级医院综合服务能力培训课件
- 化工设备检修安全技术概述课件
- 四年级下册英语Unit2WhattimeisitPartA课时课件
- 化工设备常用零部件图样及结构选用概述课件
- 加强学习履行职责做一名称职的党务干部支部书记培训课件2
- 医务人员艾滋病病毒职业暴露的预防及处理课件
- 四年级上第四单元三位数乘两位数解决问题课件
- 四年级数学上册计算工具的认识及计算课件免
- 四年级期末家长会(语文)课件