数据结构与程序设计C++描述(Kruse著)高等教育出版社-课后答案.doc
《数据结构与程序设计C++描述(Kruse著)高等教育出版社-课后答案.doc》由会员分享,可在线阅读,更多相关《数据结构与程序设计C++描述(Kruse著)高等教育出版社-课后答案.doc(800页珍藏版)》请在咨信网上搜索。
Programming Principles 1 1.2 THE GAME OF LIFE Exercises 1.2 Determine by hand calculation what will happen to each of the configurations shown in Figure 1.1 over the course of five generations. [Suggestion: Set up the Life configuration on a checkerboard. Use one color of checkers for living cells in the current generation and a second color to mark those that will be born or die in the next generation.] Answer (a) Figure remains stable. (b) (c) (d) Figure is stable. 1 2 Chapter 1 _ Programming Principles (e) (f) Figure repeats itself. (g) (h) (i) Figure repeats itself. (j) (k) (l) Figure repeats itself. Section 1.3 _ Programming Style 3 1.3 PROGRAMMING STYLE Exercises 1.3 E1. What classes would you define in implementing the following projects? What methods would your classes possess? (a) A program to store telephone numbers. Answer The program could use classes called Phone_book and Person. The methods for a Phone_book object would include look_up_name, add_person, remove_person. The methods for a Person object would include Look_up_number. Additional methods to initialize and print objects of both classes would also be useful. (b) A program to play Monopoly. Answer The program could use classes called Game_board, Property, Bank, Player, and Dice. In addition to initialization and printing methods for all classes, the following methods would be useful. The class Game_board needs methods next_card and operate_jail. The class Property needs methods change_owner, look_up_owner, rent, build, mortgage, and unmortgage. The class Bank needs methods pay and collect. The class Player needs methods roll_dice, move_location, buy_property and 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 initialization and printing methods. The class Game_board would also need methods make_move and is_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 classes Car, Traffic_light, and Queue. The classes would all need initialization and printing methods. The class Traffic_light would need additional methods change_status and status. The class Queue would need additional methods add_car and remove_car. E2. Rewrite the following class definition, which is supposed to model a deck of playing cards, so that it conforms to our principles of style. class a { // a deck of cards int X; thing Y1[52]; /* 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 card off the deck } ; Answer class Card_deck { Card deck[52]; int top_card; public: Card_deck( ); void Shuffle( ); Card deal( ); }; 4 Chapter 1 _ Programming Principles E3. Given the declarations int a[n][n], i, j; where n is a constant, determine what the following statement does, and rewrite the statement to accomplish the same effect in a less tricky way. for (i = 0; i < n; i..) for (j = 0; j < n; j..) a[i][j] = ((i . 1)/(j . 1)) * ((j . 1)/(i . 1)); Answer This statement initializes the array a with all 0’s except for 1’s down the main diagonal. A less tricky way to accomplish this initialization is: for (i = 0; i < n; i..) for (j = 0; j < n; j..) if (i == j) a[i][j] = 1; else a[i][j] = 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 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. Rewrite each function with meaningful variable names, 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 = 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 part assume the declaration typedef float vector[max]; float figure (vector vector1) { int loop1, loop4; float loop2, loop3; loop1 = 0; loop2 = vector1[loop1]; loop3 = 0.0; loop4 = loop1; for (loop4 = 0; loop4 < max; loop4..) { loop1 = loop1 . 1; loop2 = vector1[loop1 − 1]; loop3 = loop2 . loop3; } loop1 = loop1 − 1; loop2 = 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..) total += v[i]; 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 = 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 mystery(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); else if (peach > apple) if (peach > orange) return(orange); else return(peach); else return(apple); } Answer The function mystery returns the middle value of its three parameters. 6 Chapter 1 _ Programming Principles int 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 > b else if (c > b) return c; // a >= c > b else return b; // a > b >= c else if (c > b) return b; // c > b >= a else if (c > a) return c; // b >= c > a else return a; // b >= a >= c } E6. The following statement is designed to check the relative sizes of three integers, which you may assume to be different from each other: if (x < z) if (x < y) if (y < z) c = 1; else c = 2; else if (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; else if (z < x) if (z < y) c = 8; else c = 9; else c = 10; (a) Rewrite this statement in a form that is easier to read. Answer if (x < z) if (x < y) // x < z and x < y if (y < z) c = 1; // x < y < z else c = 2; // x < z <= y else // y <= x < z if (y < z) c = 3; // y <= x < z else c = 4; // impossible else // z <= x if (x < y) // z <= x < y if (x < z) c = 5; // impossible else c = 6; // z <= x < y else // z <= x and y <= x if (y < z) c = 7; // y < z <= x // z <= y <= x if (z < x) // z <= y <= x, z < x if (z < y) c = 8; // z < y <= x else c = 9; // z == y < x, impossible else c = 10; // y <= z == x, impossible (b) Since there are only six possible orderings for the three integers, only six of the ten cases can actually occur. 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 their removal we have: if (x < z) if (x < y) // x < z and x < y if (y < z) c = 1; // x < y < z else c = 2; // x < z <= y else c = 3; // y <= x < z else // z <= x if (x < y) c = 6; // z <= x < y else // z <= x and y <= x if (y < z) c = 7; // y < z <= x else c = 8; // z <= y <= x Section 1.3 _ Programming Style 7 (c) Write a simpler, shorter statement that accomplishes the same result. Answer if ((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 ((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, then z . 2y . x=y2 3 cube roots is a closer approximation. float function 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) flag = 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 nothing to the understanding, with a better layout, 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 the formula, tim plays the role of y, and tom and april both play the role of z. The object tiny is a small constant which serves as a tolerance to stop the loop. The variable shadow is nothing but 2y and square is y2 . The complicated two-line if statement checks whether the absolute value jz3 − 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 eliminating the redundant ones gives: const double tolerance = 0.00001; double cube_root(double x) // Find cube root of x by Newton method { double 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 calculating the cube root of x directly from the mathematical formula, by starting with the assignment y = x and then repeating y = (2 * y . (x/(y * y)))/3 until abs(y * y * y − x) < 0.00001. 8 Chapter 1 _ Programming Principles Answer const double tolerance = 0.00001; double formula(double x) // Find cube root of x directly from formula { double 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 written program. E8. The mean of a sequence of numbers is their sum divided by the count of numbers in the sequence. The statistics (population) variance of the sequence is the mean of the squares of all numbers in the sequence, minus the square of the mean of the numbers in the sequence. The standard deviation is the square root of the variance. Write a well-structured C++ function to calculate the standard deviation of a sequence of n floating-point numbers, where n is a constant and the numbers are in an array indexed from 0 to n−1, which is a parameter to the function. Use, then write, subsidiary functions to calculate the mean and variance. Answer #include <math.h> double variance(double v[], int n); double standard_deviation(double v[], int n) // Standard deviation of v[] { return sqrt(variance(v, n)); } This function uses a subsidiary function to calculate the variance. double mean(double v[], int n); double variance(double v[], int n) // Find the variance for n numbers in v[] { int i; double temp; double sum_squares = 0.; for (i = 0; i < n; i..) sum_squares += v[i] * v[i]; 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) // Find the mean of an array of n numbers { int i; double sum = 0.0; for (i = 0; i < n; i..) sum += v[i]; return sum/n; } Section 1.3 _ Programming Style 9 E9. Design a program that will plot a given set of points on a graph. The input to the program will be a text file, each line of which contains two numbers 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 involve plotting the specificmethod of plotting and cannot be written since they depend on the requirements of the plotting equipment, which we do not know. Before plotting the points the program needs to know the maximum and minimum values of x and y that appear in its input file. The program should therefore use another function bounds that will read the whole file and determine these four maxima and minima. Afterward, another function is used to draw and label the axes; then the file can be reset and the individual points plotted. (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 coordinates from file and plot coordinate pairs. { ifstream file(argv[1]); if (file == 0) { cout << "Can not open input points file" << endl; cout << "Usage:\n\t plotter input_points " << endl; exit(1); } double xmax, xmin; // bounds for x values double ymax, ymin; // bounds for y values double x, y; // x, y values to plot bounds(file, xmax, xmin, ymax, ymin); draw_axes(xmax, xmin, ymax, ymin); file.seekg(0, ios :: beg); // reset to beginning of file while (!file.eof( )) { file >> x >> y; plot(x, y); } } (b) Write the function bounds. Answer void bounds(ifstream &file, double &xmax, double &xmin, double &ymax, double &ymin) // determine maximum and minimum values for x and y { double 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 < ymin) ymin = y; 10 Chapter 1 _ Programming Principles if (y > ymax) ymax = y; } } (c) Write the preconditions and postconditions for the remaining functions together with appropriate documentation showing their purposes and their requirements. Answer void draw_axes(double xmax, double xmin, double ymax, double 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)- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 数据结构 程序设计 C+ 描述 Kruse 高等教育出版社 课后 答案
咨信网温馨提示:
1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前自行私信或留言给上传者【xrp****65】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时私信或留言给本站上传会员【xrp****65】,需本站解决可联系【 微信客服】、【 QQ客服】,若有其他问题请点击或扫码反馈【 服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【 版权申诉】”(推荐),意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:4008-655-100;投诉/维权电话:4009-655-100。
1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前自行私信或留言给上传者【xrp****65】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时私信或留言给本站上传会员【xrp****65】,需本站解决可联系【 微信客服】、【 QQ客服】,若有其他问题请点击或扫码反馈【 服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【 版权申诉】”(推荐),意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:4008-655-100;投诉/维权电话:4009-655-100。
关于本文