面向?qū)ο蟮腃++程序設(shè)計(jì) 第六版 課后習(xí)習(xí)題答案 第十章_第1頁
面向?qū)ο蟮腃++程序設(shè)計(jì) 第六版 課后習(xí)習(xí)題答案 第十章_第2頁
面向?qū)ο蟮腃++程序設(shè)計(jì) 第六版 課后習(xí)習(xí)題答案 第十章_第3頁
面向?qū)ο蟮腃++程序設(shè)計(jì) 第六版 課后習(xí)習(xí)題答案 第十章_第4頁
面向?qū)ο蟮腃++程序設(shè)計(jì) 第六版 課后習(xí)習(xí)題答案 第十章_第5頁
已閱讀5頁,還剩27頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、Chapter 10DEFINING CLASSES AND ABSTRACT DATA TYPES1. Solutions for and Remarks on Selected Programming ProblemsThis chapter can be done after Chapter 7, Arrays. However, I have not used anything from that chapter in these solutions. Several of these solutions could be simplified in good measure if a

2、rrays were used instead of the extensive switch and nested if else statements.1. Class grading programI have put statements of programming strategy and of the problem in the program comments.Onestruct StudentRecord int studentNumber; double quiz1; double quiz2; double midterm; double final; double a

3、verage; char grade;void input(StudentRecord& student);void computeGrade(StudentRecord& student);void output(const StudentRecord student);int main() StudentRecord studentCLASS_SIZE; for(int i = 0; i < CLASS_SIZE; i+) input(studenti); << "These are 100 point testsn" cin >

4、> >> ; cout << << " " << << endl << endl;void computeGrade(StudentRecord& student)n" abort(); = letterGradeindex;void output(const StudentRecord student) cout << "The record for student number: " << << endl <<

5、; "The quiz grades are: " << << " " << << endl << "The midterm and exam grades are: " << << " " << << endl << "The numeric average is: " << << endl << "and the letter

6、grade assigned is " << << endl;Data for the test run:1 7 10 90 952 9 8 90 803 7 8 70 804 5 8 50 705 4 0 40 35Command line command to execute the text run:ch10prg1 < dataOutput:enter the student number: 1enter two 10 point quizes7 10enter the midterm and final exam grades. These a

7、re 100 point tests90 95enter the student number: 2enter two 10 point quizes9 8enter the midterm and final exam grades. These are 100 point tests90 80enter the student number: 3enter two 10 point quizes7 8enter the midterm and final exam grades. These are 100 point tests70 80enter the student number:

8、 4enter two 10 point quizes5 8enter the midterm and final exam grades. These are 100 point tests50 70enter the student number: 5enter two 10 point quizes4 0enter the midterm and final exam grades. These are 100 point tests40 35The record for student number: 1The quiz grades are: 7 10The midterm and

9、exam grades are: 90 95The numeric average is: and the letter grade assigned is AThe record for student number: 2The quiz grades are: 9 8The midterm and exam grades are: 90 80The numeric average is: and the letter grade assigned is BThe record for student number: 3The quiz grades are: 7 8The midterm

10、and exam grades are: 70 80The numeric average is: and the letter grade assigned is CThe record for student number: 4The quiz grades are: 5 8The midterm and exam grades are: 50 70The numeric average is: and the letter grade assigned is DThe record for student number: 5The quiz grades are: 4 0The midt

11、erm and exam grades are: 40 35The numeric average is: and the letter grade assigned is F*/2. Redefine CDAccount from Display to be a class rather than struct.Use the same variables, make them private.Add member functions:to return initial balanceto return balance at maturityto return interest rateto

12、 return the termdefault constructorconstructor to set specified valuesinput function (istream&);output function (ostream&);Embed in a test programThe code in Display makes the behavior of the required functions clear. Note on capitalization schemes: I use a slightly different capitalization

13、scheme than the author. You should make your conventions clear to the student. Any capitalization that produces readable code is acceptable to this author. The instructor, as always, is left free to do as is wished.CD account, different interfaceRedo the definition of class CDAccount from Project 2

14、so that the interface is the same but the implementation is different. The new implementation is similar to the second implementation of BankAccount in Display . Here the balance is recorded in two int values, one for dollars, one for cents. The member variable for interest rate stores the interest

15、as a fraction rather than a percentage. Term is stored as in Project 2.Remark: The changes to be made are in the functions that take balance as argument. The implementation of the members must change:1) to generate the int objects dollars and cents from the external representation of balance (a doub

16、le)2) to take dollars and cents (int objects) from the internal representation and generate the external erest rate is a double (decimal) fraction rather term is stored the same #include <iostream>using namespace std;class CDAccountpublic: CDAccount(); CDAccount(double bal, doub

17、le intRate, int T ); double InterestRate(); double InitialBalance(); double BalanceAtMaturity(); int Term(); void input(istream&); void output(ostream&);private: No Answer Provided5. No Answer Provided6. Class MonthHere we create an abstract data type to represent month.The class month has t

18、he following member functions:a constructor to set month based on the first 3 letters of the name(uses 3 char args)a constructor to set month base on month number, 1 = January etc.a default constructor (what does it do)an input function to set the month based on the month numberan input function to

19、set the month based on a three-character inputan output function that outputs the month as an integer,an output function that outputs the month as the letters.a function that returns the next month as a Month objectNB each input and output function have a single formal parameter forthe streamData st

20、ore is an int object.This problem doesn't say anything about error checking. It is easy and (I hope) obvious how to do error checking. I will require my students put it in, and I use it here. The careful reader will note that testing is not thorough. It is an excellent exercise to provide test d

21、ata that makes coverage complete. (Complete coverage is to test all possible paths through the program.)With these comments, here is the code a the solution to the problem:#include <fstream> Month(); Month nextMonth(); This access member added for Not neede in this problemint Month:monthNumber

22、() return mnth;Month Month:nextMonth() int nextMonth = mnth + 1; if (nextMonth = 13) nextMonth = 1; return Month(nextMonth);Month:Month( int monthNumber) mnth = monthNumber;void Month:outputMonthNumber( ostream& in ) void Month:outputMonthName(ostream& out) We don't have one yet. if (1 =

23、 mnth) out << "Jan" else if (2 = mnth) out << "Feb" else if (3 = mnth) out << "Mar" else if (4 = mnth) out << "Apr" else if (5 = mnth) out << "May" else if (6 = mnth) out << "Jun " else if (7 = mnth) out

24、<< "Jul " else if (8 = mnth) out << "Aug" else if (9 = mnth) out << "Sep" else if (10 = mnth) out << "Oct" else if (11 = mnth) out << "Nov" else if (12 = mnth) out << "Dec"void error(char c1, char c2, cha

25、r c3) cout << endl << c1 << c2 << c3 << " is not a month. Exitingn" exit(1);void error(int n) cout << endl << n << " is not a month number. Exiting" << endl; exit(1);void Month:getMonthByNumber(istream& in) in >> mnt

26、h; void Month:getMonthByName(istream& in) .) which exits, if the month name is wrong. char c1, c2, c3; in >> c1 >> c2 >> c3; c1 = tolower(c1); int main() cout << "testing constructor Month(char, char, char)" << endl; Month m; m = Month( 'j', 'a

27、', 'n'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'f', 'e', 'b'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'm', 'a', 'r'); ( cout ); cout << " " (cout);

28、 cout << endl; m = Month( 'a', 'p', 'r'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'm', 'a', 'y'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'j', 'u', 'n&#

29、39;); ( cout ); cout << " " (cout); cout << endl; m = Month( 'j', 'u', 'l'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'a', 'u', 'g'); ( cout ); cout << " " (cout); cout <<

30、endl; m = Month( 's', 'e', 'p'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'o', 'c', 't'); ( cout ); cout << " " (cout); cout << endl; m = Month( 'n', 'o', 'v'); ( cout );

31、 cout << " " (cout); cout << endl; m = Month( 'd', 'e', 'c'); ( cout ); cout << " " (cout); cout << endl; cout << endl << "Testing Month(int) constructor" << endl; int i = 1; while (i <= 12) Month mm(i

32、); ( cout ); cout << " " (cout); cout << endl; i = i+1; cout << endl << "Testing the getMonthByName and outputMonth* n" i = 1; Month mm; while (i <= 12) (cin); ( cout ); cout << " " (cout); cout << endl; i = i+1; cout << endl

33、 << "Testing getMonthByNumber and outputMonth* " << endl; i = 1; while (i <= 12) (cin); (cout); cout << " " (cout); cout << endl; i = i+1; cout << endl << "end of loops" << endl; cout << endl << "Testing next

34、Month member" << endl; cout << "current month " (cout); cout << endl; cout << "next month " ().outputMonthNumber(cout); cout << " " ().outputMonthName(cout); cout << endl; cout << endl << "new Month created "

35、; << endl; Month mo(6); cout << "current month " (cout); cout << endl; cout << "nextMonth " ().outputMonthNumber(cout); cout << " " ().outputMonthName(cout); cout << endl; return 0;/*A testing run follows:$testing constructor Month(ch

36、ar, char, char)1 Jan2 Feb3 Mar4 Apr5 May6 Jun7 Jul8 Aug9 Sep10 Oct11 Nov12 DecTesting Month(int) constructor1 Jan */7. Redefine the implementation of class Month from #6. Store the month as 3 chars. Remarks: This will cause a permutation of the code in the various functions. Where in #5 we had to ge

37、nerate a month number from a three letter month name in a member function and in a constructor, here we will need to have this code in functions that tell us the month as an integer. Input functions such as getMonthByNumber, the constructor Month(int) will have to have table lookup to generate the t

38、hree characters.8. Rewrite program from Display Rewrite program from Display but use class Month from #5 or #6 as the type of the member variable to record the month. Redefine the member function output so that it has one formal parameter of type ostream. Cause all output to the screen to be also wr

39、itten to a file. Input is still from keyboard. Only the output is sent to a file.I have marked the start and end This #include "" #include <fstream>#include <cstdlib >#include <cctype>using namespace std;class DayOfYearpublic: void input(); void set(int newMonth, int newD

40、ay); int getMonth(); .12 = Dec int getDay(); . " << endl; (); cout << "Today's date is " outStream << "Today's date is " (cout); cout << endl; (outStream); outStream << endl; ( 3, 21); cout << ". Bach's birthday is "

41、outStream << ". Bach's birthday is " (cout); cout << endl; (outStream); outStream << endl; if ( () = () && () = () ) cout << "Happy Birthday Johann Sebastian!" << endl; outStream << "Happy Birthday Johann Sebastian!" <&

42、lt; endl; else cout << "Happy Unbirthday Johann Sebastian!" << endl; outStream << "Happy Unbirthday Johann Sebastian!" << endl; (); return 0;void DayOfYear:input() cout << "Enter the month as a number: " I added an access member to .Enter t

43、he month as a number: 4Enter the day of the month: 5Today's date is Apr, 5. Bach's birthday is Mar, 21Happy Unbirthday Johann Sebastian!17:36:19:/AW$ cat Today's date is Apr, 5. Bach's birthday is Mar, 21Happy Unbirthday Johann Sebastian!17:36:23:/AW$A second run:17:37:19:/AW$ Enter

44、today's date.Enter the month as a number: 3Enter the day of the month: 21Today's date is Mar, 21. Bach's birthday is Mar, 21Happy Birthday Johann Sebastian!17:37:29:/AW$ cat Today's date is Mar, 21. Bach's birthday is Mar, 21Happy Birthday Johann Sebastian!17:37:35:/AW$9. “The Li

45、ttle Red Grocery Store Counter”O(jiān)ne might start with the solution to #4 in solving this one.The class counter should provide:· A default constructor. For example, Counter(9999); provides a counter that can count up to9999 and displays 0.· A member function, void reset() that returns count t

46、o 0· A set of functions that increment digits 1 through 4:· void incr1() · A member function bool overflow(); detects overflow.Use the class to simulate the little red grocery store money counter.Display the 4 digits, the right most two are cents and tens of cents, the next to are dol

47、lars and tens of dollars. Provide keys for incrementing cents, dimes, dollars and tens of dollars. Suggestion: asdfo: a for cents, followed by 1-9 s for dimes, followed by 1-9 d for dollars, followed by 1-9 f for tens of dollars, followed by 1-9Followed by pressing the return key in each case.Adding

48、 is automatic, and overflow is reported after each operation. Overflow can be requested with the O key.Here is a tested implementation of this simulation. I do not supply output. You will probably need to adjust the PAUSE_CONSTANT for your machine, otherwise the pause can be so short as to be useles

49、s, or irritatingly long.#include <iostream>using namespace std;const int PAUSE_CONSTANT = 0; RESULTS " << "ARE NOT RELIABLE. Press Q to quit.n" cout << endl; (); (); cout << "." (); (); cout << endl; cout << "Enter a character followe

50、d by a digit 1-9:n" << "Enter a for unitsn" << " s for tensn" << " d for hundredsn" << " f for thousandsn" << " o to inquire about overflown" << "Q or q at any time to quit.n" cin >> ch; Quitti

51、ngn" return 0; if(ch = 'o') cout << "Overflow test requestedn" if() cout << "OVERFLOW HAS OCCURRED. RESULTS " << "ARE NOT RELIABLE. Press Q to quit.n" pause(); continue; n" pause(); continue; cin >> j; default: cout << &qu

52、ot;Program should never get heren" << "Fix programn" abort(); cout << "At end of switch n" return 0;. .n" for(int X = 0; X < PAUSE_CONSTANT; X+) X+; X-; void Counter:displayUnits() cout << units;void Counter:displayTens() cout << tens;void Cou

53、nter:displayHundreds() cout << hundreds;void Counter:displayThousands() cout << thousands;void Counter:reset() units = tens = hundreds = thousands = 0; overflowFlag = false; void Counter:display() cout << thousands << hundreds << tens << units ;bool Counter:overfl

54、ow() return overflowFlag;Counter:Counter():units(0), tens(0), hundreds(0), thousands(0), overflowFlag(false)Rational Number ClassThe one member function I would add is a “reduce” member function. This function should compute the greatest common divisor (GCD) of the numerator and denominator, then di

55、vide each by this number. This will reduce the fraction to lowest common terms. If this is not done, the numerator and denominator can grow, possibly far enough to cause integer overflow for int variables. Sequence for writing the member functions:The idea here is “Code in small increments then test

56、.”Write the constructors of several kinds.Write an access function for the real and imaginary parts to test the constructors. TEST.Write the less and neg functions.TESTIf you plan to write the reduce function, do it now.TEST.Write the output and input member functions.TESTWrite the arithmetic functi

57、ons, one at a time, and call the reduce function after the these functions have done their work, before returning the caller.TEST.11. << endl; (50); cout << "After another 50 miles, " << () << " gallons used." << endl; cout << endl; (); (13); (

58、100); cout << "For your gas guzzler:" << endl; cout << "After 100 miles, " << () << " gallons used." << endl; (50); cout << "After another 50 miles, " << () << " gallons used." << endl; retu

59、rn 0;2. Outline of Topics in the Chapter StructuresStructures for Diverse DataStructures as Function ArgumentsInitializing Structure ClassesDefining Classes and Member FunctionsPublic and Private MembersSummary of Some Properties of ClassesConstructors for Initialization Abstract Data TypesClasses t

60、o Produce ADTs3. General Remarks on the ChapterChapter Flexibility: This book is designed with flexibility in mind. Chapter 3, More Flow of Control, can be covered before Chapter 10 if desired. The solutions to the programming projects are done with this in mind, and either solutions are provided that are independent of the other chapter or notes are provide

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論