面向对象的C程序设计 后习题答案_第1页
面向对象的C程序设计 后习题答案_第2页
面向对象的C程序设计 后习题答案_第3页
面向对象的C程序设计 后习题答案_第4页
面向对象的C程序设计 后习题答案_第5页
已阅读5页,还剩47页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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./ch10Prg1.cpp#include using namespace std;const int CLASS_SIZE = 5;/ The problem says this is for a class, ra

3、ther than one student. One/ programming stratagem is to deal with a single student, then extend/ to treat an array of N students. /Grading Program/Policies:/ Two quizzes, 10 points each/ midterm and final exam, 100 points each/ Of grade, final counts 50%, midterm 25%, quizes25%/ Letter Grade is assi

4、gned:/ 90 or more A/ 80 or more B/ 70 or more C/ 60 or more D/ less than 60, F/ Read a students scores, / output record: scores + numeric average + assigned letter grade/ Use a struct to contain student record.struct StudentRecord int studentNumber; double quiz1; double quiz2; double midterm; double

5、 final; double average; char grade;void input(StudentRecord& student);/prompts for input for one student, sets the/structure variable members.void computeGrade(StudentRecord& student);/calculates the numeric average and letter grade.void output(const StudentRecord student);/outputs the student recor

6、 main() StudentRecord studentCLASS_SIZE; for(int i = 0; i CLASS_SIZE; i+) input(studenti); / Enclosing block fixes VC+ for loop control defined outside loop for(int i = 0; i CLASS_SIZE; i+) computeGrade(studenti); output(studenti); cout endl; return 0;void input(StudentRecord &student) cout stu

7、dent.studentNumber; cout student.studentNumber endl; cout enter two 10 point quizes student.quiz1 student.quiz2; cout student.quiz1 student.quiz2 endl; cout enter the midterm and final exam grades. student.midterm student.final; cout student.midterm student.final endl endl;void computeGrade(StudentR

8、ecord& student)/ Of grade, final counts 50%, midterm 25%, quizes25% double quizAvg= (student.quiz1 + student.quiz2)/2.0; double quizAvgNormalized = quizAvg * 10; student.average = student.final * 0.5 + student.midterm * 0.25 + quizAvgNormalized * 0.25; char letterGrade= FFFFFFDCBAA; int index = stat

9、ic_cast(student.average/10); if(index 0 | 10 = index) cout Bad numeric grade encountered: student.average endl Aborting.n; abort(); student.grade = letterGradeindex;void output(const StudentRecord student) cout The record for student number: student.studentNumber endl The quiz grades are: student.qu

10、iz1 student.quiz2 endl The midterm and exam grades are: student.midterm student.final endl The numeric average is: student.average endl and the letter grade assigned is student.grade 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 th

11、e text run:ch10prg1 dataOutput:enter the student number: 1enter two 10 point quizes7 10enter the midterm and final exam grades. These are 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 studen

12、t number: 3enter two 10 point quizes7 8enter the midterm and final exam grades. These are 100 point tests70 80enter the student number: 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

13、 midterm and final exam grades. These are 100 point tests40 35The record for student number: 1The quiz grades are: 7 10The midterm and exam grades are: 90 95The numeric average is: 91.25and the letter grade assigned is AThe record for student number: 2The quiz grades are: 9 8The midterm and exam gra

14、des are: 90 80The numeric average is: 83.75and the letter grade assigned is BThe record for student number: 3The quiz grades are: 7 8The midterm and exam grades are: 70 80The numeric average is: 76.25and the letter grade assigned is CThe record for student number: 4The quiz grades are: 5 8The midter

15、m and exam grades are: 50 70The numeric average is: 63.75and the letter grade assigned is DThe record for student number: 5The quiz grades are: 4 0The midterm and exam grades are: 40 35The numeric average is: 32.5and the letter grade assigned is F*/2. Redefine CDAccount from Display 10.1 to be a cla

16、ss rather than struct.Use the same variables, make them private.Add member functions:to return initial balanceto return balance at maturityto return interest rateto return the termdefault constructorconstructor to set specified valuesinput function (istream&);output function (ostream&);Embed in a te

17、st programThe code in Display 10.1 makes the behavior of the required functions clear. Note on capitalization schemes: I use a slightly different capitalization scheme than the author. You should make your conventions clear to the student. Any capitalization that produces readable code is acceptable

18、 to this author. The instructor, as always, is left free to do as is wished./ File: ch10Prg2.cpp/ Title: CDAccount#include using namespace std;class CDAccount public: CDAccount(); CDAccount(double bal, double intRate, int T ); double InterestRate(); double InitialBalance(); double BalanceAtMaturity(

19、); int Term(); void input(istream&); void output(ostream&);private: double balance; double interestRate; / in PER CENT int term; / months to maturity;int main() double balance; double intRate; int term; CDAccount account = CDAccount( 100.0, 10.0, 6 ); cout CD Account interest rate: account.InterestR

20、ate() endl; cout CD Account initial balance: account.InitialBalance() endl; cout CD Account balance at maturity is: account.BalanceAtMaturity() endl; cout CD Account term is: account.Term() months endl; account.output(cout); cout Enter CD initial balance, interest rate, and term: endl; account.input

21、(cin); cout CD Account interest rate: account.InterestRate() endl; cout CD Account initial balance: account.InitialBalance() endl; cout CD Account balance at maturity is: account.BalanceAtMaturity() endl; cout CD Account term is: account.Term() months endl; account.output( cout ); cout balance; inSt

22、ream interestRate; inStream term;void CDAccount:output(ostream& outStream) outStream.setf(ios:fixed); outStream.setf(ios:showpoint); outStream.precision(2); outStream when your CD matures in term months endl it will have a balance of BalanceAtMaturity() endl;/*A typical run follows:CD Account intere

23、st rate: 10CD Account initial balance: 100CD Account balance at maturity is: 105CD Account term is: 6 monthswhen your CD matures in 6 monthsit will have a balance of 105.00Enter CD initial balance, interest rate, and term:2001012CD Account interest rate: 10.00CD Account initial balance: 200.00CD Acc

24、ount balance at maturity is: 220.00CD Account term is: 12 monthswhen your CD matures in 12 monthsit will have a balance of 220.00*/3. CD account, different interfaceRedo the definition of class CDAccount from Project 2 so that the interface is the same but the implementation is different. The new im

25、plementation is similar to the second implementation of BankAccount in Display 10.7. Here the balance is recorded in two int values, one for dollars, one for cents. The member variable for interest rate stores the interest as a fraction rather than a percentage. Term is stored as in Project 2.Remark

26、: 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 double)2) to take dollars and cents (int objects) from the internal representatio

27、n and generate the external information./File: ch10Prg3.cpp/Title: CDAccount - modification of Program1, but with /different implementation but SAME interface./The new implementation should be similar to Display 10.7/record balance as two int values: One for dollars, one for/cents. interest rate is

28、a double (decimal) fraction rather /than a percent (0.043, not 4.3%). term is stored the same / way as Program 1.#include using namespace std;class CDAccountpublic: CDAccount(); CDAccount(double bal, double intRate, int T ); double InterestRate(); double InitialBalance(); double BalanceAtMaturity();

29、 int Term(); void input(istream&); void output(ostream&);private: / double balance; / double interestRate; / in PER CENT int dollars; int cents; double interestRate; / decimal fraction: 0.043 rather than 4.3% int term; / months to maturity;CDAccount:CDAccount() / do nothingCDAccount:CDAccount(double

30、 bal, double intRate, int T ) dollars = int(bal); cents = int(bal*100); interestRate = intRate/100; term = T;double CDAccount:InterestRate() return interestRate*100; / internal decimal frac, /external, percentdouble CDAccount:InitialBalance() return dollars + cents/100.00;double CDAccount:BalanceAtM

31、aturity() return (dollars + cents/100.0)* (1+ (interestRate)*(term/12.0);int CDAccount:Term() return term;void CDAccount:input(istream& inStream) double dBal; inStream dBal; dollars = int(dBal); cents = int(dBal - dollars)*100); inStream interestRate/100; inStream term;void CDAccount:output(ostream&

32、 outStream) outStream.setf(ios:fixed); outStream.setf(ios:showpoint); outStream.precision(2); outStream when your CD matures in term months endl it will have a balance of BalanceAtMaturity() endl;int main() double balance; double intRate; int term; CDAccount account = CDAccount( 100.0, 10.0, 6 ); co

33、ut CD Account interest rate: account.InterestRate() endl; cout CD Account initial balance: account.InitialBalance() endl; cout CD Account balance at maturity is: account.BalanceAtMaturity() endl; cout CD Account term is: account.Term() months endl; account.output( cout ); cout Enter CD initial balan

34、ce, interest rate, and term: endl; account.input(cin); cout CD Account interest rate: account.InterestRate() endl; cout CD Account initial balance: account.InitialBalance() endl; cout CD Account balance at maturity is: account.BalanceAtMaturity() endl; cout CD Account term is: account.Term() months

35、endl; account.output( cout ); cout endl;/*A typical run follows:CD Account interest rate: 10CD Account initial balance: 200CD Account balance at maturity is: 210CD Account term is: 6 monthswhen your CD matures in 6 monthsit will have a balance of 210.00Enter CD initial balance, interest rate, and te

36、rm:2001012CD Account interest rate: 10.00CD Account initial balance: 200.00CD Account balance at maturity is: 220.00CD Account term is: 12 monthswhen your CD matures in 12 monthsit will have a balance of 220.00*/4. No Answer Provided5. No Answer Provided6. Class MonthHere we create an abstract data

37、type to represent month.The class month has the 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

38、based on the month numberan input function to 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

39、a single formal parameter forthe streamData store is an int object.This problem doesnt 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 i

40、s an excellent exercise to provide test data 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:/file: ch10prb5.cpp/Title: Month/To create and test a month ADT/ Begin month.cpp for Pr

41、oblem 7 HERE.#include / for file and iostream stuff#include / for exit()#include / for tolower()class Monthpublic: Month(char c1, char c2, char c3); / done, debugged /constructor to set month based on first /3 chars of the month name Month( int monthNumber); / done, debugged /a constructor to set mo

42、nth base on month number, /1 = January etc. Month(); / done, no debugging to do /a default constructor (what does it do? nothing) void getMonthByNumber(istream&); / done, debugged /an input function to set the month based on the /month number void getMonthByName(istream&); / done, debugged /input fu

43、nction to set the month based on a three /character input void outputMonthNumber(ostream&); / done, debugged /an output function that outputs the month as an integer, void outputMonthName(ostream&); / done, debugged /an output function that outputs the month as the letters. Month nextMonth(); / /a f

44、unction that returns the next month as a month object /NB: each input and output function have a single formal /parameterfor the stream. This access member added for /Problem 7, not needed in Problem 5 int monthNumber();private: int mnth;/added for Problem 7. Not neede in this problemint Month:month

45、Number() 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 ) /cout The current month is ; / only for debugging cout mnth;/ This implementa

46、tion could profit greatly from use of / an array.void Month:outputMonthName(ostream& out) / a switch is called for. We dont have one yet. if (1 = 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

47、; else if (7 = mnth) out 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, char c3) cout endl c1 c2 c3 is not a month. Exitingn; exit(1);void error(int n) cout endl n is not

48、 a month number. Exiting mnth; / int Month:mnth;/ use of an array and linear search could help this/ implementation.void Month:getMonthByName(istream& in) /Calls error(.) which exits, if the month name is wrong. /An enhancement would be to allow the user to fix this. char c1, c2, c3; in c1 c2 c3; c1 = tolower(c1); /force to lower case so any case c2 = tolower(c2); /the user enters is acceptable c3 = tolower(

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论