面向对象的C++程序设计 第六版 课后习题答案 第十五章

合集下载

C面向对象程序设计课后习题答案1~14章

C面向对象程序设计课后习题答案1~14章
c1=getchar(); //将输入的第一个字符赋给c1
c2=getchar(); //将输入的第二个字符赋给c2
cout<<"用putchar函数输出结果为:";
putchar(c1);
putchar(44);
putchar(c2);
cout<<endl;
cout<<"用cout语句输出结果为:";
putchar(c2);
cout<<endl;
cout<<"用cout语句输出结果为:";
cout<<c1<<c2<<endl;
return 0;
}
3-4-1、#include <iostream>
using namespace std;
int main ( )
{char c1,c2;
cout<<"请输入两个字符c1,c2:";
cout<<"please enter score of student:";
cin>>score;
while (score>100||score<0)
{cout<<"data error,enter data again.";
cin>>score;
}
switch(int(score/10))
{case 10:
else m=y;
if (z<m) m=z;
return(m);
}
1-8、#include <iostream>

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)第二章2-4#includeusing namespace std;Add(int a,int b);int main(){int x,y,sum;cout>x>>y;sum = add(x,y);cout >*p;p++;}p = p-20;for( i=0;i0) countp++;if(*p>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"< }return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。

age 是类的私有成员(2)构造函数应当给常数据成员和引用成员初始化,将构造函数改为:A(int a1,int b1):a(a1),b(b1){}或A(int a1 ):a(a1),b(a){}再将main中的A a(1,2); 改为A a(1);(3)(1)在Test 类中添加语句:void print();void Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}改为void Test::Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}main函数中Init(38,15);改为:A.Init(38,15);Print();改为:A.Print();3-8(1)Constructing AConstructing BDestructing BDestructing A(2)double a,double bpoint & pp.x3-9class box{int len1,len2,len3;public:box(int l1,int l2,int l3){len1 = l1;len2 = l2; len3 = l3;} long volumn(){return len1*len2*len3;}};3-10class Test{int m1,m2;public:void Init(int a,int b){m1 = a;m2 = b;}void Pring(){cout<<m1<<" "<<m2<<endl;}};3-11略3-12}第四章4-6(1)D (2)D (3)D (4)D (5)B(6)D4-7(1)static int count = 0;这样初始化静态成员值是不对的将其改为static int count;在类外,main函数前加int Sample::count = 0;(2)#include//#includeusing namespace std;class Ctest{private:int x; const int y1;public:const int y2;Ctest(int i1,int i2):y1(i1),y2(i2) {y1 =10;//y1 为常量不能赋值x = y1;}int readme() const;};int Ctest::readme ()const{int i;i = x;x++; //常函数内不能改变成员值return x;}int main(){Ctest c(2,8);int i = c.y2;c.y2 = i;//y2为常量,不能改值i = c.y1;//y1私有,类外不能访问return 0;}将出错语句全部注释4-8(1)题中印刷错误,将class C构造函数改为: C(){cout<<"constructor C:";}运行结果为:constructor Aconstructor Bconstructor C(2)40(3)3434-9#include#includeclass Date{int year;int month;int day;public:Date(int y,int m,int d){year=y;month=m;day=d;}void disp(){cout<<year<<" "<<month<<" "<<day<<endl;}friend int count_day(Date &d,int k);friend int l(int year);friend int h(Date &d1,Date &d2);};int count_day(Date &d,int k){static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,3 1},{31,29,31,30,31,30,31,31,30,31,30,31}};// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年int j,i,s;if(l(d.year))j=1;//闰年,取1else j=0;//非闰年,取0if(k)//K非0时{s=d.day;for(i=1;i<d.month;i++)//d.month为输入的月份s+=day_tab[j][i-1];}else//K为0时{s=day_tab[j][d.month]-d.day;for(i=d.month+1; i<=12; i++)s+=day_tab[j][i-1];}return s;//S为相差的天数}int l(int year){if(year%4==0&&year%100!=0||year%400==0) // 是闰年return 1;else // 不是闰年return 0;}int h(Date &d1,Date &d2){int days,day1,day2,y;if(d1.year<d2.year)//第一个日期年份小于第二个日期年份{days=count_day(d1,0);for(y=d1.year+1;y<d2.year;y++)if(l(y))//闰年。

面向对象的C++程序设计 第六版 课后习题答案第二章

面向对象的C++程序设计 第六版 课后习题答案第二章

Chapter 2C++ Basics1. Solutions to the Programming Projects:1. Metric - English units ConversionA metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal.Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply:1 metric tons14 ounces * * = 0.000397 metric tons35,273 ouncesThe use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons.Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:const double ouncesPerMetric_ton = 35272.92; metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal:boxesPerMetricTon = 1 / metricTonsPerBox;Once this analysis is made, the code proceeds quickly://Purpose: To convert cereal box weight from ounces to // metric tons to compute number of boxes to make up a // metric ton of cereal.#include <iostream>using namespace std;const double ouncesPerMetricTon = 35272.92;int main(){double ouncesPerBox, metricTonsPerbox,boxesPerMetricTon;char ans = 'y';while( 'y' == ans || 'Y' == ans ){cout << “enter the weight in ounces of your”<< “favorite cereal:” <<end l;cin >> ouncesPerBox;metricTonsPerbox =ouncesPerBox / ouncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerbox;cout << "metric tons per box = "<< metricTonsPerbox << endl;cout << "boxes to yield a metric ton = "<< boxesPerMetricTon << endl;cout << " Y or y continues, any other character ”<< “terminates." << endl;cin >> ans;}return 0;}A sample run follows:enter the weight in ounces of your favorite cereal:14metric tons per box = 0.000396905boxes to yield a metric ton = 2519.49Y or y continues, any other characters terminates.yenter the weight in ounces of your favorite cereal:20metric tons per box = 0.000567007boxes to yield a metric ton = 1763.65Y or y continues, any other characters terminates.n2. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired to know how much soda a dieter can drink without dying. The problem statement gives no information about how to scale the amount of toxicity from the dimensions of the experimental mouse to the dimensions of the dieter. Hence the student must supply this necessary assumption as basis for the calculation.This solution supposes the lethal dose is directly proportional to the weight of the subject, henceweightOfDieterlethalDoseDieter = lethalDoseMouse *weightOfMouseThis program accepts weight of a lethal dose for a mouse, the weight of the mouse, and the weight of the dieter, and calculates the amount of sweetener that will just kill the dieter, based on the lethal dose for a mouse in the lab. If the student has problems with grams and pounds, a pound is 454 grams.It is interesting that the result probably wanted is a safe number of cans, while all the data can provide is the minimum lethal number! Some students will probably realize this, but my experience is that most will not. I just weighed a can of diet pop and subtracted the weight of an empty can. The result is about 350 grams. The label claims 355 ml, which weighs very nearly 355 grams. To get the lethal number of cans from the number of grams of sweetener, you need the number of grams ofsweetener in a can of pop, and the concentration of sweetener, which the problem assumes 0.1% , that is a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseDieter / (0.35 grams / can)////Input: lethal dose of sweetener for a lab mouse, weights// of mouse and dieter, and concentration of sweetener in a // soda.//Output: lethal dose of soda in number of cans.//Assumption: lethal dose proportional to weight of subject// Concentration of sweetener in the soda is 1/10 percent #include <iostream>using namespace std;const double concentration = .001; // 1/10 of 1 percentconst double canWeight = 350;const double gramsSweetnerPerCan = canWeight concentration; //units of grams/canint main(){double lethalDoseMouse, lethalDoseDieter,weightMouse, weightDieter; //units: gramsdouble cans;char ans;do{cout << "Enter the weight of the mouse in grams"<< endl;cin >> weightMouse;cout << "Enter the lethal dose for the mouse in“<< ”grams " << endl;cin >> lethalDoseMouse;cout << "Enter the desired weight of the dieter in”<<“ grams " << endl;cin >> weightDieter;lethalDoseDieter =lethalDoseMouse weightDieter/weightMouse;cout << "For these parameters:\nmouse weight: "<< weightMouse<< " grams " << endl<< "lethal dose for the mouse: "<< lethalDoseMouse<< "grams" << endl<< "Dieter weight: " << weightDieter<< " grams " << endl<< "The lethal dose in grams of sweetener is: "<< lethalDoseDieter << endl;cans = lethalDoseDieter / gramsSweetnerPerCan;cout << "Lethal number of cans of pop: "<< cans << endl;cout << "Y or y continues, any other character quits"<< endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}A typical run follows:17:23:09:~/AW$ a.outEnter the weight of the mouse in grams15Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 15 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 302667 Lethal number of cans of pop: 864762Y or y continues, any other character quitsyEnter the weight of the mouse in grams30Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 30 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 151333 Lethal number of cans of pop: 432381Y or y continues, any other character quitsq17:23:56:~/AW$3. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This program is to accept the previous annual salary, then outputs the retroactive pay due the employee, the new annual salary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulae are:const double INCREASE = 0.076;newSalary = salary * (1 + INCREASE);monthly = salary / 12;retroactive = (salary – oldSalary)/2;The code follows:////Given 6 mos retroactive 7.6% pay increase,//input salary//Output new annual and monthly salaries, retroactive pay#include <iostream>using namespace std;const double INCREASE = 0.076;int main(){double oldSalary, salary, monthly, retroactive;char ans;cout << "Enter current annual salary." << endl<< "I'll return new annual salary, monthly ”<< “salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarysalary = oldSalary*(1+INCREASE);//new annual salarymonthly = salary/12;retroactive = (salary – oldSalary)/2;cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}17:50:12:~/AW$ a.outEnter current annual salary.100000I'll return new annual salary, monthly salary, andretroactive pay.new annual salary 107600new monthly salary 8966.67retroactive salary due: 38004. Retroactive Salary// File: Ch2.4.cpp// Modify program from Problem #3 so that it calculatesretroactive// salary for a worker for a number of months entered by the user. //Given a 7.6% pay increase,//input salary//input number of months to compute retroactive salary//Output new annual and monthly salaries, retroactive pay#include <iostream>const double INCREASE = 0.076;int main(){using std::cout;using std::cin;using std::endl;double oldSalary, salary, monthly, oldMonthly, retroactive;int numberOfMonths; // number of months to pay retroactiveincreasechar ans;cout << "Enter current annual salary and a number of months\n"<< "for which you wish to compute retroactive pay.\n"<< "I'll return new annual salary, monthly "<< "salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarycin >> numberOfMonths;salary = oldSalary * (1+INCREASE); //new annual salaryoldMonthly = oldSalary/12;monthly = salary/12;retroactive = (monthly - oldMonthly) * numberOfMonths;// retroactive = (salary - oldSalary)/2; // six monthsretroactive pay increase.cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}/*Typical runEnter current annual salary and a number of monthsfor which you wish to compute retroactive pay.I'll return new annual salary, monthly salary, and retroactive pay. 120009new annual salary 12912new monthly salary 1076retroactive salary due: 684Press any key to continue*/5. No solution provided.6. No solution provided.7. PayrollThis problem involves payroll and uses the selection construct. A possible restatement: An hourly employee's regular payRate is $16.78/hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours, then (hoursWorked -40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax is 6% and Federal income tax is 14%. Union dues of$10/week are withheld. If there are 3 or more covered dependents, $15 more is withheld for dependent health insurance.a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each withholding amount, and net (take-home) pay.b) Add 'repeat at user discretion' feature.I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero and went directly to the next input! You either have to either use an array of char, or 9 char variables to avoid this restriction.Otherwise, the code is fairly straight forward.//file //pay roll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////This is the 'repeat at user discretion' version//Outline://In a real payroll program, each of these values would be//stored in a file after the payroll calculation was printed //to a report.////regular payRate = $10.78/hour for hoursWorked <= 40//hours.//If hoursWorked > 40 hours,// overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE.//FICA (social security) tax rate is 6%//Federal income tax rate is 14%.//Union dues = $10/week .//If number of dependents >= 3// $15 more is withheld for dependent health insurance.//#include <iostream>using namespace std;const double PAY_RATE = 16.78;const double SS_TAX_RATE = 0.06;const double FedIRS_RATE = 0.14;const double STATE_TAX_RATE = 0.05;const double UNION_DUES = 10.0;const double OVERTIME_FACTOR = 1.5;const double HEALTH_INSURANCE = 15.0;int main(){double hoursWorked, grossPay, overTime, fica,incomeTax, stateTax, union_dues, netPay;int numberDependents, employeeNumber;char ans;//set the output to two places, and force .00 for cents cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);// compute payrolldo{cout << "Enter emplo yee SSN (digits only,”<< “ no spaces or dashes) \n”;cin >> employeeNumber ;cout << “Please the enter hours worked and number “<< “of employees.” << endl;cin >> hoursWorked ;cin >> numberDependents;cout << endl;if (hoursWorked <= 40 )grossPay = hoursWorked * PAY_RATE;else{overTime =(hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR; grossPay = 40 * PAY_RATE + overTime;}fica = grossPay * SS_TAX_RATE;incomeTax = grossPay * FedIRS_RATE;stateTax = grossPay * STATE_TAX_RATE;netPay =grossPay - fica - incomeTax- UNION_DUES - stateTax;if ( numberDependents >= 3 )netPay = netPay - HEALTH_INSURANCE;//now print report for this employee:cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl; cout << "regular pay rate: " << PAY_RATE << endl;if (hoursWorked > 40 ){cout << "overtime hours worked: "<< hoursWorked - 40 << endl;cout << "with overtime premium: "<< OVERTIME_FACTOR << endl;}cout << "gross pay: " << grossPay << endl;cout << "FICA tax withheld: " << fica << endl;cout << "Federal Income Tax withheld: "<< incomeTax << endl;cout << "State Tax withheld: " << stateTax << endl;if (numberDependents >= 3 )cout << "Health Insurance Premium withheld: "<< HEALTH_INSURANCE << endl;cout << "Flabbergaster's Union Dues withheld: "<< UNION_DUES << endl;cout << "Net Pay: " << netPay << endl << endl;cout << "Compute pay for another employee?”<< “ Y/y repeats, any other ends" << endl;cin >> ans;} while( 'y' == ans || 'Y' == ans );return 0;}//A typical run:14:26:48:~/AW $ a.outEnter employee SSN (digits only, no spaces or dashes) 234567890Please the enter hours worked and number of employees.101Employee number: 234567890hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Flabbergaster's Union Dues withheld: 10.00Net Pay: 115.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 987654321Please the enter hours worked and number of employees.103Employee number: 987654321hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 80.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 123456789Please the enter hours worked and number of employees.453Employee number: 123456789hours worked: 45.00regular pay rate: 16.78overtime hours worked: 5.00with overtime premium: 1.50gross pay: 797.05FICA tax withheld: 47.82Federal Income Tax withheld: 111.59State Tax withheld: 39.85Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 552.79Compute pay for another employee? Y/y repeats, any other ends n14:28:12:~/AW $8. No solution provided.9. Installment Loan TimeNo down payment, 18 percent / year, payment of $50/month, payment goes first to interest, balance to principal. Write a program that determines the number of months it will take to pay off a $1000 stereo. The following code also outputs the monthly status of the loan.#include <iostream>using namespace std;// chapter 2 problem 9.int main(){double principal = 1000.;double interest, rate = 0.015;int months = 0;cout << "months\tinterest\tprincipal" << endl;while ( principal > 0 ){months++;interest = principal * rate;principal = principal - (50 - interest);if ( principal > 0 )cout << months << "\t" << interest << "\t\t"<< principal << endl;}cout << "number of payments = " << months;//undo the interation that drove principal negative: principal = principal + (50 - interest);//include interest for last month:interest = principal * 0.015;principal = principal + interest;cout << " last months interest = " << interest;cout << " last payment = " << principal << endl;return 0;}Testing is omitted for this problem.10. No solution provided.11. Separate numbers by sign, compute sums and averages// Programming Problem 11// Read ten int values output// sum and average of positive numbers// sum and average of nonpositive numbers,// sum and average of all numbers,//// Averages are usually floating point numbers.We mulitply// the numerator of the average computation by 1.0 to make// the int values convert automatically to double.#include <iostream>int main(){using std::cout;using std::cin;using std::endl;int value, sum = 0, sumPos = 0, sumNonPos = 0;int countPos = 0, countNeg = 0;cout << "Enter ten numbers, I'll echo your number and compute\n"<< "the sum and average of positive numbers\n"<< "the sum and average of nonpositive numbers\n"<< "the sum and average of all numbers\n\n";for(int i =0; i < 10; i++){cin >> value;cout << "value " << value <<endl;sum += value;if (value > 0){sumPos += value;countPos++;}else{sumNonPos += value;countNeg++;}}cout << "Sum of Positive numbers is "<< sumPos << endl;cout << "Average of Positive numbers is "<< (1.0 * sumPos) / countPos << endl;cout << "Sum of NonPositive numbers is "<< sumNonPos << endl;cout << "Average of NonPositive numbers is "<< (1.0 * sumNonPos) / countNeg << endl;cout << "Sum " << sum << endl;cout << "Average is " << (1.0 * sum)/(countPos + countNeg) << endl;if((countPos + countNeg)!= 10)cout << "Count not 10, error some place\n";return 0;}/*Typical runEnter ten numbers, I'll echo your number and computethe sum and average of positive numbersthe sum and average of nonpositive numbersthe sum and average of all numbers4value 45value 5-1value -13value 3-4value -4-3value -39value 98value 87value 72value 2Sum of Positive numbers is 38Average of Positive numbers is 5.42857Sum of NonPositive numbers is -8Average of NonPositive numbers is -2.66667Sum 30Average is 3Press any key to continue*/12.//***********************************************************************// Ch2Proj12.cpp//// This program computes the square root of a number n// using the Babylonian algorithm.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double guess, previousguess, n, r;// Input number to compute the square root ofcout << "Enter number to compute the square root of." << endl;cin >> n;// Initial guesspreviousguess = n;guess = n /2;// Repeat until guess is within 1% of the previous guesswhile (((previousguess - guess) / previousguess) > 0.01){previousguess = guess;r = n / guess;guess = (guess + r) / 2;}cout << "The estimate of the square root of " << n << " is "<< guess << endl;return 0;}13.//*********************************************************************** // Ch2Proj13.cpp//// This program inputs a speed in MPH and converts it to// Minutes and Seconds per mile, as might be output on a treadmill.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double milesPerHour, hoursPerMile, minutesPerMile, secondsPace;int minutesPace;// Input miles per hourcout << "Enter speed in miles per hour:" << endl;cin >> milesPerHour;// Compute inverse, which is hours per milehoursPerMile = 1.0 / milesPerHour;// Convert to minutes per mile which is 60 seconds/hour * hoursPerMile minutesPerMile = 60 * hoursPerMile;// Extract minutes by converting to an integer, while// truncates any value after the decimal pointminutesPace = static_cast<int>(minutesPerMile);// Seconds is the remaining number of minutes * 60secondsPace = (minutesPerMile - minutesPace) * 60;cout << milesPerHour << " miles per hour is a pace of " << minutesPace << " minutes and " << secondsPace << " seconds. " << endl;return 0;}14.//*********************************************************************** // Ch2Proj14.cpp//// This program plays a simple game of "Mad Libs".//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){string instructorName;string yourName;string food;int num;string adjective;string color;string animal;cout << "Welcome to Mad Libs! Enter your name: " << endl;cin >> yourName;cout << "Enter your instructor's first or last name." << endl;cin >> instructorName;cout << "Enter a food." << endl;cin >> food;cout << "Enter a number between 100 and 120." << endl;cin >> num;cout << "Enter an adjective." << endl;cin >> adjective;cout << "Enter a color." << endl;cin >> color;cout << "Enter an animal." << endl;cin >> animal;cout << endl;cout << "Dear Instructor " << instructorName << "," << endl;cout << endl;cout << "I am sorry that I am unable to turn in my homework at this time."<< endl;cout << "First, I ate a rotten " << food << " which made me turn " << color << " and " << endl;cout << "extremely ill. I came down with a fever of " << num << "." << endl;cout << "Next, my " << adjective << " pet " << animal << " must have " <<"smelled the remains " << endl;cout << "of the " << food << " on my homework, because he ate it. I am " <<"currently " << endl;cout << "rewriting my homework and hope you will accept it late." << endl;cout << endl;cout << "Sincerely," << endl;cout << yourName << endl;return 0;}2. Outline of topics in the chapter2.1 Variables and assignments2.2 Input and Output2.3 Data Types and Expressions2.4 Simple Flow of Controlbranchinglooping2.5 Program Style3. General Remarks on the chapter:This chapter is a very brief introduction to the minimum C++ necessary to write simple programs.Comments in the Student's code:Self documenting code is a code feature to be striven for. The use of identifier names that have meaning within the context of the problems being solved goes a long way in this direction.Code that is not self documenting for whatever reasons may be made clearer by appropriate (minimal) comments inserted in the code."The most difficult feature of any programming language to master is thecomment."-- a disgruntled maintenance programmer."Where the comment and the code disagree, both should be assumed to be inerror."-- an experienced maintenance programmer.With these cautions in mind, the student should place remarks at the top of file containing program components, describing the purpose. Exactly what output is required should be specified, and any conditions on the input to guarantee correct execution should also bespecified.Remarks can clarify difficult points, but remember, if the comment doesn't add to what can be gleaned from the program code itself, the comment is unnecessary, indeed it gets in the way. Good identifier names can reduce the necessity for comments!iostreams vs stdioYou will have the occasional student who has significant C programming experience. These students will insist on using the older stdio library input-output (for example, printf). Discourage this, insist on C++ iostream i/o. The reason is that the iostream library understands and uses the type system of C++. You have to tell stdio functions every type for every output attempted. And if you don't get it right, then the error may not be obvious in the output. Either iostreams knows the type, or the linker will complain that it doesn't have the member functions to handle the type you are using. Then it is easy enough to write stream i/o routines to do the i/o in a manner consistent with the rest of the library.。

面向对象的C++程序设计-第六版-课后习题答案第四章

面向对象的C++程序设计-第六版-课后习题答案第四章

Chapter 4Procedural Abstraction and Functions That Return a Value1. Solutions to and Remarks on Selected Programming Problems1. No solution provided.2. No solution provided.3. Value of Stock HoldingsThis program asks for input of the price of a stock, the number of stocks owned, and outputs the value of the stock holding in dollars and cents. The program should define a function that accepts the price of the stock in three int values: whole dollars, numerator of fraction, and denominator of the fraction, then outputs the value of the stock as a double. For example, for a stock whose price was 7 7/8 dollars, the input would be 7 7/8 and the output would be 7.87 (using a "5's round odd" rule.) In supervised student labs, I find the error of having a function prototype different in some essential way than the function definition to be a prevalent error.The Algorithm in Pseudocode and in code://required function://return value = dollars+num/denom with appropriate casts//double convert (int dollars, int num, int denom)//get price with fraction, number of shares//call function to convert price with fraction to price as double//value = price * (number of shares)//output value//Program://file //problem: take input of number of shares, price as dollars,//numerator and denominator of fractional part of price, give//value of holdings.double convert(int dollars, int num, int den);//accept as input the stock price with fraction, return//price as double#include <iostream>using namespace std;int main(){int dollars, numer, denom, shares;double price, value;cout << "Enter stock price and number of shares, please.\n"<< "Enter price as integers: dollars, numerator, “<< “denominator." << endl;cin >> dollars >> numer >> denom;cout << "Enter number of shares held." << endl;cin >> shares;price = convert(dollars, numer, denom);value = price shares;cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);cout << shares << " shares of stock with market price "<< dollars << " " << numer << "/" << denom << endl<< "have value $" << value << endl;return 0;}double convert (int dollars, int num, int den){return dollars + double(num)/den;}A typical run follows.14:24:24:~/AW$ a.outEnter stock price and number of shares, please.Enter price as integers: dollars, numerator, denominator.10 5 8Enter number of shares held.100100 shares of stock with market price 10 5/8have value $1062.5014:24:32:~/AW$4. No solution provided.5. No solution provided.6. Credit Card InterestThis program computes interest on a credit card balance. The task is done with a function that accepts initial balance, monthly interest rate, number of months for which the interest must be paid. The value returned is the interest due. Allow repeat at user's option. NB Interest is compounded. Function is to be embed in a program that acquires these values and outputs the interest due. Repeat of computation at users option is to be allowed.Algorithm in pseudocode:Function name: interestinput: fetch values for:double initBalance, double rate, int months.process:declare balance = initBalance, interest;declare index = 0;while (index < months){balance = balance (1 + rate);months++;}interest = balance - initBalance;output: interestmain:declare balance rate, interestEarned, months。

面向对象的C++程序设计 第六版 课后习题答案 第十章

面向对象的C++程序设计 第六版 课后习题答案 第十章

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 arrays 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 <iostream>using namespace std;const int CLASS_SIZE = 5;// The problem says this is for a class, rather 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 assigned:// 90 or more A// 80 or more B// 70 or more C// 60 or more D// less than 60, F//// Read a student's 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 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 record.int main(){StudentRecord student[CLASS_SIZE];for(int i = 0; i < CLASS_SIZE; i++)input(student[i]);// Enclosing block fixes VC++ "for" loop control defined outside loop { for(int i = 0; i < CLASS_SIZE; i++){computeGrade(student[i]);output(student[i]);cout << endl;}}return 0;}void input(StudentRecord &student){cout << "enter the student number: ";cin >> student.studentNumber;cout << student.studentNumber << endl;cout << "enter two 10 point quizes" << endl;cin >> student.quiz1 >> student.quiz2;cout << student.quiz1 << " " << student.quiz2 << endl; cout << "enter the midterm and final exam grades."<< "These are 100 point tests\n";cin >> student.midterm >> student.final;cout << student.midterm << " " << student.final<< endl << endl;}void computeGrade(StudentRecord& 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 = static_cast<int>(student.average/10);if(index < 0 || 10 <= index){cout << "Bad numeric grade encountered: "<< student.average << endl<< " Aborting.\n";abort();}student.grade = letterGrade[index];}void output(const StudentRecord student){cout << "The record for student number: "<< student.studentNumber << endl<< "The quiz grades are: "<< student.quiz1 << " " << 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 the text run:ch10prg1 < dataOutput:enter the student number: 1enter two 10 point quizes7 10enter the midterm and final exam grades. These are 100 point tests 90 95enter the student number: 2enter two 10 point quizes9 8enter the midterm and final exam grades. These are 100 point tests 90 80enter the student number: 3enter two 10 point quizes7 8enter the midterm and final exam grades. These are 100 point tests 70 80enter the student number: 4enter two 10 point quizes5 8enter the midterm and final exam grades. These are 100 point tests 50 70enter the student number: 5enter two 10 point quizes4 0enter the midterm and final exam grades. These are 100 point tests 40 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 grades 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 midterm 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 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 return the termdefault constructorconstructor to set specified valuesinput function (istream&);output function (ostream&);Embed in a test 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 thatproduces readable code is acceptable to this author. The instructor, as always, is left free to do as is wished.// File: ch10Prg2.cpp// Title: CDAccount#include <iostream>using namespace std;class CDAccount{public:CDAccount();CDAccount(double bal, double intRate, int T );double InterestRate();double InitialBalance();double BalanceAtMaturity();int Term();void input(istream&);void output(ostream&);private:double balance;double interestRate; // in PER CENTint 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.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 balance, 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"<< endl;account.output( cout );cout << endl;}CDAccount::CDAccount() { /* do nothing */ } CDAccount::CDAccount(double bal, double intRate, int T ) {balance = bal;interestRate = intRate;term = T;}double CDAccount::InterestRate(){return interestRate;}double CDAccount::InitialBalance(){return balance;}double CDAccount::BalanceAtMaturity(){return balance * (1+ (interestRate /100)*(term/12.0)); }int CDAccount::Term(){return term;}void CDAccount::input(istream& inStream){inStream >> balance;inStream >> 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 interest 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 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*/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 implementation 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: 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 representation 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 a double (decimal) fraction rather //than a percent (0.043, not 4.3%). term is stored the same // way as Program 1.#include <iostream>using namespace std;class CDAccount{public:CDAccount();CDAccount(double bal, double intRate, int T );double InterestRate();double InitialBalance();double BalanceAtMaturity();int Term();void input(istream&);void output(ostream&);private:// double balance;// double interestRate; // in PER CENTint dollars;int cents;double interestRate; // decimal fraction: 0.043 rather than 4.3%int term; // months to maturity;};CDAccount::CDAccount(){// do nothing}CDAccount::CDAccount(double 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, percent}double CDAccount::InitialBalance(){return dollars + cents/100.00;}double CDAccount::BalanceAtMaturity(){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& 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 );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 << "Enter CD initial balance, 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"<< 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 term: 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 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 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 a single formal parameter forthe streamData store 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 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 Problem 7 HERE.#include <fstream> // for file and iostream stuff#include <cstdlib> // for exit()#include <cctype> // for tolower()class Month{public:Month(char c1, char c2, char c3); // done, debugged//constructor to set month based on first//3 chars of the month nameMonth( int monthNumber); // done, debugged//a constructor to set month 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 numbervoid getMonthByName(istream&); // done, debugged//input function to set the month based on a three//character inputvoid 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 function 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 5int monthNumber();private:int mnth;};//added for Problem 7. Not neede in this problemint Month::monthNumber(){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 implementation could profit greatly from use of// an array.void Month::outputMonthName(ostream& out){// a switch is called for. We don't 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 ";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.Exiting\n";exit(1);}void error(int n){cout << endl << n << " is not a month number. Exiting" << endl;exit(1);}void Month::getMonthByNumber(istream& in){in >> 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 casec2 = tolower(c2); //the user enters is acceptablec3 = tolower(c3);if ('j' == c1)if ('a' == c2)mnth = 1; // janelse if ('u' == c2)if ('n' == c3)mnth = 6; // junelse if ('l' == c3)mnth = 7; // julelse error(c1, c2, c3); // ju, not n orelse error(c1, c2, c3); // j, not a or uelse if ('f' == c1)if ('e' == c2)if ('b' == c3)mnth = 2; // febelse error(c1, c2, c3); // fe, not belse error(c1, c2, c3); // f, not eelse if ('m' == c1)if ('a' == c2)if('y' == c3)mnth = 5; // mayelse if('r' == c3)mnth = 3; // marelse error(c1, c2, c3); // ma not a, r else error(c1,c2,c3); // m not a or relse if ('a' == c1)if ('p' == c2)if ('r' == c3)mnth = 4; // aprelse error(c1, c2, c3 ); // ap not relse if('u' == c2)if ('g' == c3)mnth = 8; // augelse error(c1,c2,c3); // au not gelse error(c1,c2,c3); // a not u or pelse if ('s' == c1)if ('e' == c2)if ('p' == c3)mnth = 9; // sepelse error(c1, c2, c3); // se, not pelse error(c1, c2, c3); // s, not eelse if ('o' == c1)if ('c' == c2)if ('t' == c3)mnth = 10; // octelse error(c1, c2, c3); // oc, not telse error(c1, c2, c3); // o, not celse if ('n' == c1)if ('o' == c2)if ('v' == c3)mnth = 11; // novelse error(c1, c2, c3); // no, not velse error(c1, c2, c3); // n, not oelse if ('d' == c1)if ('e' == c2)if ('c' == c3)mnth = 12; // decelse error(c1, c2, c3); // de, not celse error(c1, c2, c3); // d, not eelse error(c1, c2, c3); // c1 not j, f, m, a, s, o, n, or d }Month::Month(char c1, char c2, char c3){c1 = tolower(c1);c2 = tolower(c2);c3 = tolower(c3);if ('j' == c1)if ('a' == c2)mnth=1; // janelse if ('u' == c2)if ('n' == c3)mnth = 6; // junelse if ('l' == c3)mnth = 7; // julelse error(c1, c2, c3); // ju, not n orelse error(c1, c2, c3); // j, not a or uelse if ('f' == c1)if ('e' == c2)if ('b' == c3)mnth = 2; // febelse error(c1, c2, c3); // fe, not belse error(c1, c2, c3); // f, not eelse if ('m' == c1)if ('a' == c2)if ('y' == c3)mnth = 5; // mayelse if('r' == c3)mnth = 3; // marelse error(c1, c2, c3); // ma not a, r else error(c1,c2,c3); // m not a or relse if ('a' == c1)if ('p' == c2)if ( 'r' == c3)mnth = 4; // aprelse error(c1, c2, c3 ); // ap not relse if('u' == c2)if ('g' == c3)mnth = 8; // augelse error(c1,c2,c3); // au not gelse error(c1,c2,c3); // a not u or pelse if ('s' == c1)if ('e' == c2)if ('p' == c3)mnth = 9; // sepelse error(c1, c2, c3); // se, not pelse error(c1, c2, c3); // s, not eelse if ('o' == c1)if ('c' == c2)if ('t' == c3)mnth = 10; // octelse error(c1, c2, c3); // oc, not telse error(c1, c2, c3); // o, not celse if ('n' == c1)if ('o' == c2)if ('v' == c3)mnth = 11; // novelse error(c1, c2, c3); // no, not velse error(c1, c2, c3); // n, not oelse if ('d' == c1)if ('e' == c2)if ('c' == c3)mnth = 12; // decelse error(c1, c2, c3); // de, not celse error(c1, c2, c3); // d, not eelse error(c1, c2, c3); // c1 not j, f, m, a, s, o,//n, or d}Month::Month(){// body deliberately empty}//END month.cpp for Problem 7 HERE.int main(){cout << "testing constructor Month(char, char, char)" << endl;Month m;m = Month( 'j', 'a', 'n');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'f', 'e', 'b');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'm', 'a', 'r');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'a', 'p', 'r');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'm', 'a', 'y');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'j', 'u', 'n');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'j', 'u', 'l');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'a', 'u', 'g');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 's', 'e', 'p');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'o', 'c', 't');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'n', 'o', 'v');m.outputMonthNumber( cout ); cout << " "; m.outputMonthName(cout); cout << endl;m = Month( 'd', 'e', 'c');m.outputMonthNumber( cout ); cout << " ";m.outputMonthName(cout); cout << endl;cout << endl << "Testing Month(int) constructor" << endl; int i = 1;while (i <= 12){Month mm(i);mm.outputMonthNumber( cout ); cout << " ";mm.outputMonthName(cout); cout << endl;i = i+1;}cout << endl<< "Testing the getMonthByName and outputMonth* \n";i = 1;Month mm;while (i <= 12){mm.getMonthByName(cin);mm.outputMonthNumber( cout ); cout << " ";mm.outputMonthName(cout); cout << endl;i = i+1;}cout << endl<< "Testing getMonthByNumber and outputMonth* "<< endl;i = 1;while (i <= 12){mm.getMonthByNumber(cin);mm.outputMonthNumber(cout); cout << " ";mm.outputMonthName(cout); cout << endl;i = i+1;}cout << endl << "end of loops" << endl;cout << endl << "Testing nextMonth member" << endl; cout << "current month ";mm.outputMonthNumber(cout); cout << endl;cout << "next month ";mm.nextMonth().outputMonthNumber(cout); cout << " "; mm.nextMonth().outputMonthName(cout); cout << endl; cout << endl << "new Month created " << endl;Month mo(6);cout << "current month ";mo.outputMonthNumber(cout); cout << endl;cout << "nextMonth ";mo.nextMonth().outputMonthNumber(cout); cout << " "; mo.nextMonth().outputMonthName(cout); cout << endl; return 0;}/*A testing run follows:$a.outtesting constructor Month(char, 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 generate 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 three characters.8. Rewrite program from Display 10.4Rewrite program from Display 10.4 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 written to a file. Input is still from keyboard. Only the output is sent to a file.//File: ch10prb7.cpp//Note: The file month.cpp contains the definition and//implementation of class month and its members from problem //5, done to save room here. I have marked the start and end //of the file month.cpp in the solution to Problem 5. This//should be copied from the solution as month.cpp, in the//current directory or folder.。

c面向对象程序设计课后习题答案

c面向对象程序设计课后习题答案

c面向对象程序设计课后习题答案C面向对象程序设计课后习题答案在学习C面向对象程序设计课程的过程中,课后习题是巩固知识、提升能力的重要途径。

通过认真完成习题,我们可以更好地理解课程内容,掌握编程技巧,提高解决问题的能力。

下面我们将针对一些常见的C面向对象程序设计课后习题进行答案解析。

1. 请编写一个C++程序,实现一个简单的学生信息管理系统,包括学生姓名、学号、成绩等信息的录入、查询和修改功能。

答案解析:首先,我们需要定义一个学生类,包括姓名、学号、成绩等属性,并实现相应的方法来实现信息的录入、查询和修改功能。

然后在主函数中创建学生对象,调用相应的方法即可实现学生信息管理系统。

2. 编写一个C++程序,实现一个简单的图书管理系统,包括图书名称、作者、出版社等信息的录入、查询和删除功能。

答案解析:同样地,我们需要定义一个图书类,包括图书名称、作者、出版社等属性,并实现相应的方法来实现信息的录入、查询和删除功能。

在主函数中创建图书对象,调用相应的方法即可实现图书管理系统。

3. 设计一个C++程序,模拟实现一个简单的银行账户管理系统,包括账户余额、存款、取款等功能。

答案解析:在这个问题中,我们需要定义一个银行账户类,包括账户余额、存款、取款等属性,并实现相应的方法来实现账户管理系统。

在主函数中创建账户对象,调用相应的方法即可实现银行账户管理系统。

通过以上习题的解答,我们可以看到C面向对象程序设计的重要性和实际应用。

通过不断地练习和实践,我们可以更好地掌握面向对象程序设计的知识和技能,提高编程能力,为今后的工作和学习打下坚实的基础。

希望同学们能够认真对待课后习题,不断提升自己的编程水平。

面向对象程序设计C课后题答案

面向对象程序设计C课后题答案

第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。

这种范型的主要特征是:程序=对象+消息。

面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。

第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。

面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。

这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。

[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。

对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。

类和对象之间的关系是抽象和具体的关系。

类是多个对象进行综合抽象的结果,一个对象是类的一个实例。

在面向对象程序设计中,总是先声明类,再由类生成对象。

类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。

[1_3]现实世界中的对象有哪些特征?请举例说明。

对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。

(2)需要用属性来描述它的某些特性。

(3)有一组操作,每一个操作决定了对象的一种行为。

(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。

例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。

c 面向对象程序设计教程习题答案

c 面向对象程序设计教程习题答案

c 面向对象程序设计教程习题答案C面向对象程序设计教程习题答案在学习C面向对象程序设计的过程中,习题答案是非常重要的一部分。

通过练习习题,可以加深对知识点的理解,提高编程能力。

下面我们就来看一些常见的C面向对象程序设计习题及其答案。

1. 什么是面向对象程序设计?面向对象程序设计是一种程序设计范式,它以对象为中心,通过封装、继承和多态等特性来组织和管理代码。

面向对象程序设计可以提高代码的可维护性和可重用性,是现代软件开发中非常重要的一部分。

2. 什么是类和对象?类是一种抽象的数据类型,它描述了一类对象的共同特征和行为。

对象是类的实例,它具体描述了一个具体的实体。

在C面向对象程序设计中,类和对象是非常重要的概念。

3. 请编写一个简单的类和对象的例子。

```c#include <stdio.h>// 定义一个简单的类class Person {public:int age;char name[20];void display() {printf("Name: %s, Age: %d\n", name, age);}};int main() {// 创建一个对象Person p;p.age = 25;strcpy(, "Alice");p.display();return 0;}```4. 什么是封装?封装是面向对象程序设计中的一种重要特性,它将数据和行为封装在一个类中,对外部隐藏了内部的实现细节。

封装可以保护数据的安全性,同时提供了简单的接口供外部访问。

5. 请编写一个简单的封装例子。

```c#include <stdio.h>// 定义一个简单的类class Circle {private:double radius;public:void setRadius(double r) {radius = r;}double getArea() {return 3.14 * radius * radius;}};int main() {// 创建一个对象Circle c;c.setRadius(5.0);printf("Area: %f\n", c.getArea());return 0;}```以上就是一些常见的C面向对象程序设计习题及其答案。

面向对象的c++程序设计第六版课后习题答案第十章

面向对象的c++程序设计第六版课后习题答案第十章
2) to take dollars and cents (int objects) from the internal representation and generate the external information.
interest rate is a double (decimal) fraction rather
1. Class grading program
I have put statements of programming strategy and of the problem in the program comments.
One
struct StudentRecord
{
int studentNumber;
90 95
enter the student number: 2
enter two 10 point quizes
9 8
enter the midterm and final exam grades. These are 100 point tests
90 80
enter the student number: 3
double InitialBalance();
double BalanceAtMaturity();
int Term();
void input(istream&);
void output(ostream&);
private:
No Answer Provided
5. No Answer Provided
enter two 10 point quizes
7 8
enter the midterm and final exam grades. These are 100 point tests

C 面向对象程序设计习题解答(全)

C  面向对象程序设计习题解答(全)

4答案 n=2,sum=2 n=3,sum=5 n=5,sum=10
5答案 x=3 6答案 x=1,y=2 x=30,y=40 7答案 1 2 3 4 exit main 3 2 1 8答案 n=100 9答案 the student is:Li Hu the teacher is:Wang Ping 10答案 2 11答案 1035,789.504 12答案 13答案
一、选择题 1 2 3 4 D B B C
类和对象的进一步解析
5 D 6 D 7 D B 8 C B 9 10 11 12 13 14 15 16 B D B A A C B A
17 18 19 20 21 22 23 24 C C D B A D 二、填空题 1 this 2所有成员 3友元类、友元函数 4 friend 5 程序编译、程序结束 三、程序阅读题
第六章 派生与继承
一、选择题 1(1) 1(2) 2 A B 3 4 5 6 7 8 9 10 11 D C C C D D B C A D
二、填空题 1 继承 2 具体化、抽象 3 公有继承、保护继承、私有继承 4 子对象 5 public(共有的)、protected(保护的)、不可访问 6 protected(保护的)、protected(保护的)、不可访问的 7 private(私有的)、private(私有的)、不可访问的 8 二义性 三、判断下列描述的正确性 1 2 3 4 5 6 7 8 9 10 11 12 13 √ × × × × × √ √ × × √ √ ×
1、 选择题 1 2 3 4 5 6 7 C 8 9 10 D D D C A D C 2、 程序阅读题 1答案 a=639,b=78,c=12 2答案 a=5,b=8 a=8,b=5 3答案 10 4答案 x=20.6 y=5 z=A x=216.34 y=5 z=A x=216.34 y=2 z=A x=216.34 y=2 z=E 5答案 ic=11 fc=7.82 ic=5 fc=2.15 3、 判断下列描述的正确性 1 2 √ × D A

visual basic 程序设计课后习题参考答案

visual basic 程序设计课后习题参考答案

Visual basic 程序设计习题参考答案第一章Visual basic 程序设计一、选择题二、填空题三、简答题1、简述visual basic 的特点。

(1)具有可视化的设计平台(2)面向对象的设计方法(3)事件驱动的编程机制(4)结构化程序设计语言(5)开放的数据库功能与网络支持2、什么是对象、类、属性、事件和方法?在可视化编程语言中,对象是代码和数据的集合,它可以是窗体和控件,也可以是菜单和数据库等。

描述一个对象有三个基本要素:属性、方法和事件。

类是一组用来定义对象的相关过程和数据的集合,即同类对象的集合和抽象。

属性是描述对象的一组特性。

方法是对象能够执行的动作,它是对象本身内含的函数或过程,用于完成某种特定的功能。

事件是发生在对象上并且能够被对象识别的动作,即由系统预先设置好的、能被对象识别的动作,如Click(单击)、DblClick(双击)、Load(窗体的装载)、KeyPress(按键)、Change(改变)、MouseMove (鼠标的移动)等,每一种对象能识别的事件是不同的5、什么是事件驱动的编程机制?当某个事件(一般由用户操作来触发) 发生时,系统就会自动执行此事件的事件过程。

由事件控制整个程序的执行流程。

事件过程要经过事件的触发才能被执行,这种工作模式称为事件驱动方式。

第二章Visual basic 程序设计基础一、选择题二、填空题第三章数据输入输出一、选择题二、填空题3第四章选择结构和循环结构程序设计一、选择题二、填空题第五章数组一、选择题二、填空题第六章过程一、选择题二、填空题三、简答题1、简述事件过程和通用过程的含义和联系。

5VB应用程序是由过程组成的,过程是完成某种特殊功能的一组独立的程序代码。

VB中的过程有两大类:事件过程和通用过程事件过程是当发生某个事件时,对该事件作出响应的程序段。

事件过程由VB自行声明,用户不能增加或删除。

事件过程是VB 应用程序的主体。

c--面向对象程序设计课后习题解答-谭浩强

c--面向对象程序设计课后习题解答-谭浩强

(5)第6行末尾少了一个分号。 (6)add函数中的retrun拼写错误,应为return。编译系统把retrun作为未声明的标识符而报错 ,因为retrun(z)会被认为是函数调用的形式。 (7)变量a和b未被赋值。 改正后的程序如下: #include using namespace std; int main( {int add(int x,int y; int a,b,c; cin >> a >> b; c=add(a,b; cout <<" a+b=" << c < return 0; } int add(int x,int y {int z; z=x+y; return(z; } 运行情况如下: 5 8↙ 13 10.输入以下程序,编译并运行,分析运行结果。 #include using namespace std; int main( { void sort(int x,int y,int z; int x,y,z;
1 5 3↙ (输入3个整数
1 (输出其中最小的数
8.在你所用的C++系统上,输入以下程序,进行编译,观察编译情况,如果有错误,请修改 程序,再进行编译,直到没有错误,然后进行连接和运行,分析运行结果。
int main( ; { int a,b; c=a+b; cout >>" a+b=" >> a+b; } 【解】 上机编译出错,编译出错信息告知在第2行出错,经检查,发现第1行的末尾多了一个分号,编译 系统无法理解第2行的花括号,导致报告第2行出错。将第1行的末尾的分号去掉,重新编译,编 译出错信息告知在第5行和第6行出错。第5行出错原因是cout未经声明,因为cout不是C++语言 提供的系统的关键字,而是输出流的对象,必须使用头文件iostream。第6行出错原因是main是i nt型函数,应返回一个整型值。将程序改为

标准c程序设计第6版答案

标准c程序设计第6版答案

标准C程序设计第6版答案1. 简介本文档是《标准C程序设计第6版》一书的答案,旨在辅助读者理解和掌握书中的内容。

在学习C程序设计过程中,参考答案可以帮助读者检验自己的理解程度,加深对知识点的理解,并提供一种解题思路。

2. 第一章简介2.1 问题1答案:C语言是一种通用的计算机编程语言,广泛应用于系统软件、嵌入式系统、驱动程序等领域。

C语言被广泛使用的原因有以下几点: - 简洁高效:C语言的语法简洁,易于学习和理解。

同时,C语言的执行效率高,生成的机器代码精简,执行速度快。

- 跨平台:C语言具有很强的可移植性,可以在不同的操作系统和硬件平台上编写和运行程序。

- 底层控制能力:C语言支持直接操作内存和硬件设备,适用于需要对底层进行精确控制的场景。

- 丰富的函数库:C语言拥有丰富的函数库,方便开发者进行程序开发。

2.2 问题2答案:C语言是由贝尔实验室的Dennis Ritchie和Ken Thompson在20世纪70年代开发的。

起初,C语言是为Unix操作系统开发的,但由于其简洁高效的特点,迅速流行起来,并成为广泛应用的编程语言。

2.3 问题3答案:C语言是一种面向过程的编程语言。

它将问题分解为若干个子过程,通过调用这些子过程来解决问题。

C语言的面向过程特点使得程序的组织结构清晰,易于理解和维护。

3. 第二章程序框图与程序步骤图3.1 问题4答案:程序框图(program flowchart)是一种图形化的表示程序流程的工具。

它用不同的图形符号表示各种程序控制结构,如顺序结构、选择结构和循环结构。

程序框图通过连接这些图形符号来表示程序的执行顺序。

程序框图提供了一种清晰的视觉方式,帮助开发者理解程序的结构和流程。

3.2 问题5答案:程序步骤图(program flowchart)是一种图形化的表示程序运行步骤的工具。

它使用方框表示程序的每一步骤,通过箭头表示各个步骤之间的逻辑关系。

程序步骤图主要用于描述程序的逻辑流程,帮助开发者理解和分析程序的执行过程。

面向对象的C++程序设计 第六版 课后习题答案第三章

面向对象的C++程序设计 第六版 课后习题答案第三章

Chapter 3MORE FLOW OF CONTROL1. Solutions for and Remarks on Selected Programming ProblemsIn order to preserve flexibility of the text, the author has not dealt with classes in this chapter at all. To help those who really want to do things with classes, some of the Programming Projects will be carried out using one or several classes.1. Rock Scissors PaperHere each of two players types in one of strings "Rock", "Scissors", or "Paper". After the second player has typed in the string, the winner of this game is determined and announced.Rules:Rock breaks ScissorsScissors cuts PaperPaper covers RockIf both players give the same answer, then there is no winner.A nice touch would be to keep and report total wins for each player as play proceeds.To find the classes, we note first that there are 2 identical players. These players record the character entered, and keep track of the wins. There is a constructor that sets the total wins to 0. There is a play() member function that prompts for and gets from the keyboard returns one of the characters 'R', 'P', or 'S' for rock, paper and scissors. There is an accessor member function for ch and an incrementor member function for accumulated wins so that a stand alone function int win(ch, ch); can determine who wins and increment the accumulated wins variable.(A better solution would make the wins function a friend of class player so that wins can have access to the each player's private data to determine who wins and update the accumulated wins without the accessor function ch() and incrementWins() function.)Note that I have left a bit of debugging code in the program.class player{public function membersconstructors()play(); // prompts for and gets this player's movechar ch(); // accessorint accumulatedWins(); // accessorincrWins(); // increments win countprivate datacharacter typed inaccumulatedWins};int wins(player user1, player user2);//player1's character is compared to player2's character using accessor // functions.// wins returns// 0 if there no winner// 1 if player 1 wins,// 2 if player 2 wins,//calls the appropriate incrWins() to update the winsNote that once the class is defined and the auxiliary function written, the code “almost writes itself.”//file: //Rock Paper Scissors game//class/object solution#include <iostream>#include <cctype> //for int toupper(int);using namespace std;class Player{public:Player();void play(); //prompts for and gets this player's movechar Ch(); //accessorint AccumulatedWins(); //accessorvoid IncrWins(); //increments win countprivate:char ch; //character typed inint totalWins; //total of wins};Player::Player():totalWins(0)//intializer sets Player::totalWins to 0 {//The body is deliberately empty. This is the preferred C++ idiom. //This function could be written omitting the initializer, and//putting this line in the body://totalWins = 0;}void Player::play(){cout << "Please enter either R)ock, P)aper, or S)cissors."<< endl;cin >> ch;ch = toupper(ch); //no cast needed, ch is declared to be char}char Player::Ch(){return ch;}int Player::AccumulatedWins(){return totalWins;}void Player::IncrWins(){totalWins++;}int wins(Player& user1, Player& user2);// player1's character is compared to player2's character// using accessor functions.// The function wins returns// 0 if there no winner// 1 if player 1 wins,// 2 if player 2 wins,//calls the appropriate IncrWins() to update the winsint wins(Player& user1, Player& user2 ) // this must change user1// and user2{if( ( 'R' == user1.Ch() && 'S' == user2.Ch() )||( 'P' == user1.Ch() && 'R' == user2.Ch() )||( 'S' == user1.Ch() && 'P' == user2.Ch() ) ){// user 1 winsuser1.IncrWins();return 1;}else if( ( 'R' == user2.Ch() && 'S' == user1.Ch() )|| ( 'P' == user2.Ch() && 'R' == user1.Ch() )|| ( 'S' == user2.Ch() && 'P' == user1.Ch() ) ) {// user2 winsuser2.IncrWins();return 2;}else// no winnerreturn 0;}int main(){Player player1;Player player2;char ans = 'Y';while ('Y' == ans){player1.play();player2.play();switch( wins(player1, player2) ){case 0:cout << "No winner. " << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins() << endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play again? Y/y continues other quits";cin >> ans;cout << "Thanks " << endl;break;case 1:cout << "Player 1 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins()<< endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play Again? Y/y continues, other quits. "; cin >> ans;cout << "Thanks " << endl;break;case 2:cout << "Player 2 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins()<< endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play Again? Y/y continues, other quits.";cin >> ans;cout << "Thanks " << endl;break;}ans = toupper(ans);}return 0;}A typical run for the class/object solution follows:Please enter either R)ock, P)aper, or S)cissors.RPlease enter either R)ock, P)aper, or S)cissors.Sinside IncrWins()1Player 1 wins.Totals to this move:Player 1: 1Player 2: 0Play Again? Y/y continues, other quits. yThanksPlease enter either R)ock, P)aper, or S)cissors. SPlease enter either R)ock, P)aper, or S)cissors. Pinside IncrWins()2Player 1 wins.Totals to this move:Player 1: 2Player 2: 0Play Again? Y/y continues, other quits. yThanksPlease enter either R)ock, P)aper, or S)cissors. PPlease enter either R)ock, P)aper, or S)cissors. Sinside IncrWins()1Player 2 wins.Totals to this move:Player 1: 2Player 2: 1Play Again? Y/y continues, other quits.yThanksPlease enter either R)ock, P)aper, or S)cissors. PPlease enter either R)ock, P)aper, or S)cissors. PNo winner.Totals to this move:Player 1: 2Player 2: 1Play again? Y/y continues other quits qThanks1. Rock Scissors Paper -- Conventional solution:Here each of two players types in one of strings "Rock", "Scissors", or "Paper". After the second player has typed in the string, the winner of this game is determined and announced.Rules:Rock breaks ScissorsScissors cuts PaperPaper covers RockIf both players give the same answer, then there is no winner.A nice touch would be to keep and report total wins for each player as play proceeds.This is a conventional solution to the problem.//file //conventional solution to the Rock Scissors Paper game#include <iostream> // stream io#include <cctype> // for int toupper(int)using namespace std;int wins(char ch1, char ch2){if( ( 'R' == ch1 && 'S' == ch2 )||( 'P' == ch1 && 'R' == ch2 )||( 'S' == ch1 && 'P' == ch2 ) )return 1; // player 1 winselse if(( 'R' == ch2 && 'S' == ch1 )||( 'P' == ch2 && 'R' == ch1 )||( 'S' == ch2 && 'P' == ch1 ) )return 2; // player 2 winselsereturn 0; // no winner}char play(){char ch;cout << "Please enter either R)ock, P)aper, or S)cissors." << endl; cin >> ch;return toupper(ch); // no cast needed, char is return type}int main(){int wins_1 = 0;int wins_2 = 0;char ch1;char ch2;char ans = 'Y';while ('Y' == ans){ch1 = play();ch2 = play();switch( wins(ch1, ch2) ){case 0:cout << "No winner. " << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play again? Y/y continues other quits";cin >> ans;cout << "Thanks " << endl;break;case 1:wins_1++;cout << "Player 1 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play Again? Y/y continues, other quits. ";cin >> ans;cout << "Thanks " << endl;break;case 2:wins_2++;cout << "Player 2 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play Again? Y/y continues, other quits.";cin >> ans;cout << "Thanks " << endl;break;}ans = toupper(ans);}return 0;}A typical run follows for the co nventional solution is essentially the same as for the …class‟ based solution.2. Credit Account problem. -- class/object solutionCompute interest due, total amount due, and minimum payment for a revolving credit account.Inputs: account balanceProcess: Computes interestinterest according to:1.5% on 1st $10001.0% on all over $1000adds this to account balance get total due.Computes minimum payment according to:if amount due < $10,minimum payment is total dueelseminimum payment is 10% of total dueoutputs: Interest due, total amount due, minimum paymentThe class is the account.the public interface has functions:constructorsdefault constructorconstructor with parameter balance,computes interest, total due, minimum payinterestDue() reports interesttotalDue() reports total amount dueminPayDue() reports minimum payment dueprivate databalancetotal dueinterest dueminimum paymentClass-object Implementation://file: //Interest//class-object solution//Purpose: Compute interest due, total amount due, and minimum payment //for a revolving credit account.////Inputs: account balance////Process: Computes interest// interest according to:// 1.5% on 1st $1000 of balance// 1.0% on all over $1000 of balance// adds this to account balance get total due.// Computes minimum payment according to:// if amount due < $10,// minimum payment is total due// else// minimum payment is 10% of total due////outputs: Interest due, total amount due, minimum payment#include <iostream>using namespace std;const double INTEREST_RATE1 = 0.015;const double INTEREST_RATE2 = 0.01;const double MINPAY_FRACTION = 0.10;class CreditAccount{public:CreditAccount(); // sets everything to 0CreditAccount( double balance );// computes everything needed double interestDue();double totalDue();double minPayDue();private:double balance;double interestDue;double totalDue;double minPay;};double CreditAccount::interestDue(){return interestDue;}double CreditAccount::totalDue(){return totalDue;}double CreditAccount::minPayDue(){return minPay;}CreditAccount::CreditAccount():balance(0),totalDue(0), interestDue(0), minPay(0){//Body deliberately left empty.//This is a C++ idiom. See this IRM Chapter 10.// This is covered in Appendix 7 of the text}CreditAccount::CreditAccount( double balance ){if (balance <= 1000 )interestDue = balance*INTEREST_RATE1;else if ( balance > 1000 )interestDue = 1000*INTEREST_RATE1 + (balance - 1000)*INTEREST_RATE2; totalDue = balance + interestDue;if (totalDue <= 10 )minPay = totalDue;elseminPay = totalDue * MINPAY_FRACTION;}int main(){cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);char ans;double balance;do{cout << "Enter the account balance, please: " ;cin >> balance;CreditAccount account( balance );cout << "Interest due: " << account.interestDue() << endl<< "Total due: " << account.totalDue() << endl<< "Minimum Payment: " << account.minPayDue() << endl;cout << "Y/y repeats. any other quits" << endl;cin >> ans;}while('y' ==ans || 'Y' == ans );}A typical run for the class/object solution follows:Enter the account balance, please: 9.00Interest due: 0.14Total due: 9.13Minimum Payment: 9.13Y/y repeats. any other quitsyEnter the account balance, please: 9.85Interest due: 0.15Total due: 10.00Minimum Payment: 10.00Y/y repeats. any other quitsyEnter the account balance, please: 985.22Interest due: 14.78Total due: 1000.00Minimum Payment: 100.00Y/y repeats. any other quitsyEnter the account balance, please: 1000Interest due: 15.00Total due: 1015.00Minimum Payment: 101.50Y/y repeats. any other quitsyEnter the account balance, please: 2000Interest due: 25.00Total due: 2025.00Minimum Payment: 202.50Y/y repeats. any other quitsq2. Credit Account problem -- Conventional solutionCompute interest due, total amount due, and minimum payment for a revolving credit account. Inputs: account balanceProcess: Computes interestinterest according to:1.5% on 1st $10001.0% on all over $1000adds this to account balance get total due.Computes minimum payment according to:if amount due < $10,minimum payment is total dueelseminimum payment is 10% of total dueoutputs: Interest due, total amount due, minimum paymentdatabalancetotal dueinterest dueminimum payment//file: //conventional solution////Purpose: Compute interest due, total amount due, and minimum payment //for a revolving credit account.////Inputs: account balance////Process: Computes interest// interest according to:// 1.5% on 1st $1000 of balance// 1.0% on all over $1000 of balance// adds this to account balance get total due.// Computes minimum payment according to:// if amount due < $10,// minimum payment is total due// else// minimum payment is 10% of total due////Outputs: Interest due, total amount due, minimum payment#include <iostream>using namespace std;const double INTEREST_RATE1 = 0.015;const double INTEREST_RATE2 = 0.01;const double MINPAY_FRACTION = 0.10;double interestDue(double balance){if (balance <= 1000 )return balance*INTEREST_RATE1;return 1000*INTEREST_RATE1 + (balance - 1000)*INTEREST_RATE2; }double minPay(double totalDue){if (totalDue <= 10 )return totalDue;return totalDue * MINPAY_FRACTION;}int main(){double balance;double interestDue;double totalDue;double minPay;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);char ans;do{cout << "Enter the account balance, please: " ;cin >> balance;interestDue = interestDue(balance);totalDue = balance + interestDue;minPay = minPay(totalDue);cout << "Interest due: " << interestDue << endl<< "Total due: " << totalDue << endl<< "Minimum Payment: " << minPay << endl;cout << "Y/y repeats. any other quits" << endl;cin >> ans;}while ( 'y' ==ans || 'Y' == ans );}A typical run for the conventional solution does not differ significantly from the …class‟ based solution.3. Astrology Class/Object solution.Notes:I have not done a conventional solution. All the bits and pieces necessary to do a conventional solution are present here. I also have not done the enhancements suggested. I have, however, included comments that suggest how to carry out these enhancements.I have used slightly modified new_line and display_line code from the text. Encourage students not to reinvent the wheel, that is, to use bits and pieces code from the book and other sources as long as copyrights are not violated.I used a library book on astrology for my reference. A newspaper works as well.Planning:Input: user's birthday. Month 1-12, day 1-31Process: table lookup of signs and horoscopes, with repeat at user's optionOutput: Sign of the Zodiac and horoscope for that birthday.Hint: user a newspaper horoscope for names, dates and ahoroscope for each sign.Enhancement: If birthday is within 2 days of the adjacentsign, announce that the birthdate is on a "cusp" and outputthe horoscope for the adjacent sign also.Comments and suggestions. Program will have a long multiwaybranch. Store the horoscopes in a file.Ask your instructor for any special instructions, such as file name orlocation if this is a class assignment.Planning for the solution:What are the object and classes?The Astrological Chart would be the class if we were doing a full chart. We are only selecting the Sun Sign, but we still let Astro be the class.Zodiac Sign names and dates:Aries March 21 - April 19Tarus April 20 - May 20Gemini May 21 - June 21Cancer June 22 - July 22Leo July 23 - August 22Virgo August 23 - September 22Libra September 23 - October 22Scorpio October 23 - November 21Sagittarius November 22 - December 21Capricorn December 21 - January 19Aquarius January 19 - February 18Pices February 19 - March 20Horoscope file structure.The initial <cr> is necessary given this code to prevent output from running on from the first horoscope. (We did not make use of the sign number.)<cr>sign numberhoroscope#sign numberhoroscope#and so on.Pseudocode for the class and what member functions do...class Astro{public:constructorsAstro();Astro( Date birthday);looks up and sets the sign number,Enhancement:sets iscusp to -1 if birthday is within 2 daysbefore the adjacent sign, to -1 if within 2 daysafter adjacent sign and 0 if neither.member functionsvoid horoscope ();Enhancement:if iscusp == -1, report horoscope before thecurrent one and the current one.else if iscusp == 1, report the current horoscopeand the one following.else // iscusp == 0, do the default action:Unenhanced action:Dump the horoscopes from file up to the current one.Display current horoscope.How? # is sentinel for end of a horoscope. Dump horoscopesthrough (signNumber -1) # symbols, using utilityfunctions. Display through next # using utilityfunctions.private:Day birthday;int signNumber;void newHoroscope(istream & inStream);// display inStream to next # and discard the #void displayHoroscope( istream& sourceFile);// read and ignore inStream through the next #//Enhancement:// int isCusp(};Planning done, now to the coding. The contents of “horoscope.dat” are listed with the …typical run‟ at the end of the following code.// Program: file: // Requires file "horoscope.dat" having structure// lines of text// #// lines of text// #// ...// lines of text// ##include <fstream> //for stream io#include <stdlib> //for exit()using namespace std;// an enum could have certainly been used hereconst int aries = 1;const int taurus = 2;const int gemini = 3;const int cancer = 4;const int leo = 5;const int virgo = 6;const int libra = 7;const int scorpio = 8;const int Sagittarius = 9;const int capricorn = 10;const int aquarius = 11;const int pisces = 12;//const makes certain no error that changes these constants is made.struct month //no checking is done... Let the user be warned!{int day; // 1..28, or 29 or 30 or 31, depending on month.int month; // 1..12};class Astro{public:Astro();Astro( month birthday);// looks up and sets the sign number//Enhancement: sets iscusp to -1 if birthday is within 2 days // before the adjacent sign, to -1 if within 2 days// after adjacent sign and 0 if neither.void horoscope ();//Enhancement: if iscusp == -1,// dump (signNumber - 2) horoscopes// else if iscusp == 1// dump (signNumber - 1) horoscopes// display next two horoscopes.// return;// unenhanced action: if we get here, iscusp == 0 so we// dump (signNumber - 1) horoscopes,// display next horoscope.private:month birthday;int signNumber;void newHoroscope(istream & inStream);void displayHoroscope( istream& sourceFile);//Enhancement:// int isCusp;};// dumps all from file through the next #void Astro::newHoroscope(istream & inStream){char symbol;do{inStream.get(symbol);} while(symbol != '#' );}//displays all from file through the next #void Astro::displayHoroscope( istream& sourceFile){char next;sourceFile.get(next);while ( '#' != next ){cout << next;sourceFile.get(next);}}void Astro::horoscope(){ifstream infile;infile.open( "horoscope.dat");int c;// cusp == 0 case: dump signNumber - 1 horoscopes.for ( int i = 1; i < signNumber; i++)newHoroscope( infile );displayHoroscope( infile );cout << endl;//Enhancement, change from //cusp==0 case://so that// if (cusp == -1)// dump thru (signNumber - 2) horoscopes// else if(cusp == 1 )// dump thru (signNumber - 1) hororscopes// from this position,// display two horoscopes// return// this is the cusp = 0 case, as above.}Astro::Astro() // I prefer to use the class initializer list { // notation. This follows the textsignNumber = 0;// isCusp = 0; // for one of the enhancements I did not do }Astro::Astro( month birthday)//int signNumber( month birthday ) // to test this turkey// looks up and sets the sign number,{switch( birthday.month ){case 1:if (birthday.day <= 19) signNumber = capricorn;else signNumber = aquarius;// enhancement code will look like this in all the cases:// if ( 17 <= birthday.day && birthday.day < 19 )cusp = -1;// else if ( 19 < birthday.day && birthday.day <= 21 )cusp = -1; // else cusp = 0;//break;case 2:if ( birthday.day <= 18 ) signNumber = aquarius;else signNumber = pisces;break;case 3:if ( birthday.day <=20 ) signNumber = pisces;else signNumber = aries;break;case 4:if ( birthday.day <= 19 ) signNumber = aries;else signNumber = taurus;break;case 5:if (birthday.day <= 20 ) signNumber = taurus;else signNumber = gemini;break;case 6:if (birthday.day <= 21 ) signNumber = gemini;else signNumber = cancer;break;case 7:if (birthday.day <= 22 ) signNumber = cancer;else signNumber = leo;break;case 8:if (birthday.day <= 22 ) signNumber = leo;else signNumber = virgo;break;case 9:if (birthday.day <= 22 ) signNumber = virgo;else signNumber = libra;break;case 10:if (birthday.day <= 22 ) signNumber = libra;else signNumber = scorpio;break;case 11:if (birthday.day <= 21 ) signNumber = scorpio;else signNumber = sagittarius;break;case 12:if (birthday.day <= 21 ) signNumber = sagittarius;else signNumber = capricorn;break;default: cout << "no such month as " << birthday.month<< " Aborting " << endl;exit(1);break;}}int main(){month birthday;cout << "Any non-digit in the month field will terminate the program." << endl;cout << "Enter birthday in numeric form: month day, as 12 5 : "<< endl;cin >> birthday.month >> birthday.day;do{cout << birthday.month << " " << birthday.day;Astro user(birthday);user.horoscope();cout << "Enter birthday in numeric form: month day, as 12 5: " << endl; cin >> birthday.month >> birthday.day;} while ( cin );}Test Data and Runs.Space restrictions prohibit including a complete horoscope here for each Sun Sign. I have created an abbreviated test file for Horoscopes. (The carriage return at the start of the file is necessary to obtain acarriage return before the Aries horoscope.)$cat horoscope.dat1 Aries#2 Taurus#3 Gemini#4 Cancer#5 Leo#6 Virgo#7 Libra#8 Scorpio#9 Sagittarius#10 Capricorn#11 Aquarius#12 Pisces#A shortened typical run with the test data file following:a.out < data | lessTest data: first entry is the month, second is the day:cat data1 191 201 212 182 19several dates omitted10 2411 2011 2111 2212 2112 2212 23Output from this run:Enter birthday in numeric form: day month, as 12 5:1 1910 CapricornEnter birthday in numeric form: day month, as 12 5:1 2011 AquariusEnter birthday in numeric form: day month, as 12 5:1 2111 AquariusSeveral lines of output have been deleted.Enter birthday in numeric form: day month, as 12 5:12 219 SagittariusEnter birthday in numeric form: day month, as 12 5:12 2210 CapricornEnter birthday in numeric form: day month, as 12 5:12 2310 CapricornEnter birthday in numeric form: day month, as 12 5:4. Modify Horoscope// File: ch3.4.cpp// Modify File: ch3.3.cpp//// Modify Project 3 to request the user's birthday then// to display the three most compatible astrological signs// (having the same Element)//// Elements are Earth, Air, Fire, and Water,// Fire signs are Aries, Leo, Sagittarius// Earth signs are Taurus, Virgo, Capricorn// Air signs are Gemini, Libra, Aquarius// Water signs are Cancer, Scorpio, Pisces//// Known Bugs:// Day number is only partially verified. Program aborts if the// day number > 31. No further checking is done for day input errors // such as Feb 29 on non-leap-years or April 31.// Enhancements suggested from #3 are not implemented. Hints// on how to do the enhancements are given in strategic places// in comments.// Program: file: // Requires file "horoscope.dat" having structure// lines of text// #// lines of text。

C++面向对象程序设计(第六版)第一章编程题答案

C++面向对象程序设计(第六版)第一章编程题答案

INSTRUCTOR’S RESOURCE GUIDE SOLUTIONS TO PROGRAMMING PROJECTSTO ACCOMPANYPROBLEMSOLVINGWITHC++THE OBJECTOF PROGRAMMINGSixth EditionWalter SavitchUNIVERSITY OF CALIFORNIA, SAN DIEGOThis instructor’s manual is based on the fourth edition./savitchand please visit our general computer science and engineering web site at:/csCopyright © 2007 by Addison-Wesley Publishing CompanyAll right reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photo-copying, recording, or any other media embodiments now known or hereafter to become known, without the prior written permission of the publisher. Manufactured in the United States of America.Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where these designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.The programs and the applications presented in this book have been included for their instructional value. They have been tested with care but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications.Addison-Wesley Publishing Company2725 Sand Hill RoadMenlo Park, CA 94025ContentsPrefaceChapter 1 Introduction to Computers and C++ Programming Chapter 2 C++ BasicsChapter 3 More Flow of ControlChapter 4 Procedural Abstraction and Functions that Return a Value Chapter 5 Functions for all SubtasksChapter 6 I/O Streams as an Introduction to Objects and Classes Chapter 7 ArraysChapter 8 Strings and VectorsChapter 9 Pointers and Dynamic ArraysChapter 10 Defining ClassesChapter 11 Friends and Overloaded OperatorsChapter 12 Separate Compilation and NamespacesChapter 13 Pointers and Linked ListsChapter 14 RecursionChapter 15 InheritanceChapter 16 Exception HandlingChapter 17 TemplatesChapter 18 Standard Template LibraryPrefaceThis is a document that is meant to be a supplement the text for the instructor. There is a discussion of the ideas in each chapter, teaching suggestions, and some supplementary ideas. There are solutions to many of the programming problems. Some problems have several different solutions that correspond to different paths through the book. There are 25 to 50 test questions with answers and discussion for each chapter. The questions are of both short answer (multiple choice, true false, fill in the blank) type as well as read-the-code questions and short programming problems. I urge that explanations to the short answer questions be required of the student.With regard to the content of this manual, it should be noted that C++ leaves many options on how to do any problem, and any book will necessarily choose a subset to present. Our author has made such a set of choices. I have also made what I hope is a complementary set of choices for this Instructor's resource Manual. I am striving to produce a complementary document to the text, a document for the instructor, but I necessarily will do some things differently. Please do not hold the student responsible for what I have put here. The reader of this document must note that it is necessary to read the text, as that is what the student has to work with. In spite of our efforts at consistency of content and style, there will be some variance between some of the presentation here and the presentation in the text.The code has been compiled and tested with g++ (gcc 3.4.4), Visual Studio C++ .NET 2003, Visual Studio C++ .NET 2005, Visual Studio C++ Express .NET, and Visual Studio C++ 6.0 updated to service pack 6. Users of Microsoft Visual Studio C++ 6.0 may experience the most incompatibilities and should ensure that service pack 6 is downloaded and installed from the Microsoft website. The text uses only mainstream features of C++, consequently, most compilers will compile the code and produce output that does not differ significantly from the results presented here. We have attempted to supply warnings where any of these compilers gives trouble.Instructor's Resource ManualforSavitch, Problem Solving with C++: The Object of Programming.Chapter 1Introduction to Computers and C++ ProgrammingThis document is intended to be a resource guide for instructors using Savitch, Problem Solving with C++: The Object of Programming. This guide follows the text chapter by chapter. Each chapter of this guide contains the following sections:1. Outline of topics in the chapter2. General remarks on the chapter3. Solutions to, and remarks on, selected Programming Projects4. Test Questions5. Answers to the test QuestionSolutions and remarks on selected Programming ProjectsThese programming exercises are intended to help familiarize the student with the programming environment. Solutions are very system dependent. Consequently, only one solution is provided for the programming projects in this chapter.// Ch1Proj8.cpp//// This program calculates the monetary value of a number of// quarters, dimes, and nickels.// ***********************************************************************#include <iostream>using namespace std;// ====================// main function// ====================int main()6{int quarters, dimes, nickels, total;// Input coinscout << "Enter number of quarters." << endl;cin >> quarters;cout << "Enter number of dimes." << endl;cin >> dimes;cout << "Enter number of nickels." << endl;cin >> nickels;// Calculate and output totaltotal = (quarters * 25) + (dimes * 10) + (nickels * 5);cout << "The monetary value of your coins is " << total << " cents." << endl;return 0;}Outline of Topics in the Chapter 11.1 Computer Systems1.2 Programming and Problem-Solving1.3 Introduction to C++1.4 Testing and DebuggingSuggested course outlines:There seem to be three major approaches to teaching C++ as the first course in programming. In the one approach, classes and objects are done very early, frequently with a library of some sort that must be used with the text. In another, all of the ANSI C subset of C++ is covered prior to even mentioning classes or objects. This text takes a third road that is more middle of the road. Here, enough of the control constructs and functions are covered prior to doing classes and objects. However, reorderings of the chapters are possible that allow any of these approaches. Here is a "classes early" course that follows the text closely. This outline assumes no background in computing. Topics beyond Chapter 11 may be studied as time permits.Day days allotted1 1 Startup business2-3 2 Chapter 1: Introduction to Computers4-8 5 Chapter 2: C++ Basics. If the students have programming experience, the time spent can be significantly reduced.9-11 3 Chapter 3: Procedural Abstraction and functions that return a value712-14 3 Chapter 4: Functions for all subtasksTest 116-18 3 Chapter 5: I/O Streams as introduction to Objects and Classes19-22 4 Chapter 6: Defining Classes23-27 5 Chapter 7: More Flow of ControlTest 229-32 4 Chapter 8:Friends and Overloaded OperatorsChapter 9 Separate Compilation and Namespaces33-37 5 Chapter 10: Arrays38-41 3 Chapter 11: Strings and VectorsTest 35 Chapter 12 Pointers, Dynamic Arrays3 Chapter 13 Recursion3 Chapter 14: Templates3 Chapter 15: Pointers and Linked Lists3 Chapter 16: Inheritance3 Chapter 17: Exception HandlingReorderings:The author suggests a reordering in the preface that allow almost all of ANSI C (with the tighter C++ type-checking) to be covered before classes. Several variants on this reordering that allow classes a bit earlier are presented in the text. The author describes interdependency of the chapters in the preface of the text. Other reorderings are certainly possible.Chapter 1:The student should do all the programming assignments in this chapter. These teach the locally available program development system and familiarize the student with some of the more common compiler errors. Error messages are quite specific to the compiler being used. It is very important that the student learn these ideas as early as possible.Outline of topics in the chapter:1.1 Computer Systems1.2 Programming and Problem-Solving1.3 Introduction to C++1.4 Testing and DebuggingGeneral remarks on the chapter8This chapter serves as an introduction to computers and the language of computers for those students who have no computer experience. The terminology is very important. Many students only want to learn how the programming language works, and seem to be unhappy when they find that they are required to learn the terminology associated with the language. The students who learn the terminology have less trouble by far with this course.Students should be given an indication of the amount of work that must be done before coding begins. There are instances where several man-years of work have gone into software before a single line of code was written.Emphasize the importance of the problem-solving phase of program design. This will save the student work in the long run. It is further important to emphasize that the problem definition and algorithm design phases may need correcting once the actual coding and testing is in process. This is true even if the algorithm was carefully desktop tested. Emphasize that the program design process is an 'iterative' process. You make a start, test, correct and repeat until you have a solution.It is a fact that the sooner the coding is started (on most problems), the longer the problem will take to finish. My students insist on learning this the hard way. The algorithm design can be given a boost by dividing the problem definition into INPUT, PROCESS, OUTPUT phases. The algorithm will be primarily concerned with PROCESS, but frequently just getting information into the computer, or out of the computer in a desirable format is a significant part of the task, if not the whole problem.In the text, Section 1.4, subsection "Kinds of Program Errors", there is a discussion of compiler error messages. The error message from g++ when the wrong operator << or >> is used for input or output, is something like errormessage.cpp:8: no match for `_IO_ostream_withassign& >> int & Borland's C++ the error message is likely be something about an "illegal structure operation in function (whatever):". The point is that compiler error messages are not clear, and anything your can do to help students to associate error messages with errors that cause them will help the student to gain some intuition in debugging based on compiler messages.Encourage students to put only one statement per line. When errors are made, as they inevitably are, the compiler is better able to tell us which is the offending statement. The cost is little for the convenience gained in ability to find errors. The student should take compiler warnings to heart. If the compiler warns about something, and the student is not absolutely certain what the message is warning about, the student should treat the warning like the error that it probably is. The bottom line is that all warnings (in the first course, at least) should be treated as errors. Compilers vary with respect to what is reported as an error and what is reported with a warning. The GNU project C++ compiler, g++ is more permissive by default. Encourage your students to compile usingg++ -W -Wall --pedantic file.cppThis provides error messages that are close to the lint C-code checker. The Borland compilers are sufficiently demanding by default. GNU g++ and the Borland compilers very nearly meet the new C++ Standard. The libraries distributed with the current Borland compilers follow the C++ Standard closely. The libraries distributed with g++2.9.5 do not place names from header files without an extension into namespace std as required by the ISO Standard. However, the recently distributed g++ 3.0 does follow the ISO Standard quite closely. More will be said about this later. Gnu g++, VC++ and the Borland compilers provide options to adjustment the kinds of errors and warnings that are issued.9The student should be encouraged to ask the compiler questions about the C++ language, to create examples and to actually test the questions on the computer. The compiler is the final authority on the version of the language that the compiler accepts, regardless of the ISO Standard. An example is Programming Exercise 1, where the student is asked to type in a simple program, then test the effect of deliberately introducing common errors.10。

面向对象C++程序设计——各章习题答案

面向对象C++程序设计——各章习题答案

面向对象C++程序设计各章习题参考答案第1章面向对象技术概论一.选择题1. A2. C3. D4. B5. C二.填空题1. 封装、继承、多态性2. 面向对象分析(OOA)、面向对象设计(OOD)、面向对象实现(OOI)、面向对象测试(OOT)和面向对象系统维护(OOSM)。

3. 实例实例4. 多态性5. 消息消息传递第2章 C++简单程序设计一.选择题:1. B2. B3. B4. C5. C6. D7. D8. C9. D 10. C11. A 12. A二.填空题:1.4;2;2;8;12. 103. 04. 87;79;115. (1)x值为6,表达式的值为6(2)x值为6,但表达式的值为5(3)x值为4,表达式的值为4(4)x值为5,表达式的值为5(5)x变为6,y的值为5(6)x变为4,y的值为4(7)x变为6,y的值为25(8)x的值为6,y的值为366. const7. c+i*sizeof (c[i])8. x<=3||x>=109. a<=b&&b!=510. 30 30三.程序分析题:1.s=552.a,b99,96,194100.2,94.8,1963.i,s=15,564.13 15 22 14 645.14 25四.编程题(参考答案):1. 假设数组中含8个元素,参考答案如下:#include<iostream.h>void main(){int c=0,i,a[8],k;cout<<"input a[i]:"<<endl;for(i=0;i<8;i++)cin>>a[i];cout<<"input k:"<<endl;cin>>k;for (i=0;i<8;i++)if (a[i]>=k) c++;cout<<c;cout<<endl;}2. 参考答案:#include<iostream.h>void main(){const int n=50,m=10;int i,j,k;int index[n]; //存放学号float s,score[n],sum; //存放成绩for(i=0;i<n;i++)cin>>index[i]>>score[i]; //从键盘输入数据sum+=score[i];cout.precision(2); //设置输出宽度cout<<endl<<"A verage score:"<<sum/n; //输出平均分数cout.width(28); //设置输出宽度cout<<endl<<"Student ID:"; //输出学号for(i=0;i<10;i++) //选取前m名分数最高的学生,输出其学号及成绩{s=score[i];k=i;for(j=i+1;j<n;j++)if(s<score[j]){s=score[j];k=j;}if(k>i){score[k]=score[i];score[i]=s;j=index[k];index[k]=index[i];index[i]=j;}cout.width(4); //输出序号,学号和分数cout<<endl<<i+1;cout.width(11);cout<<index[i];cout.width(12);cout.precision(2);cout<<score[i];}cout<<endl;}3.#include<iostream.h>void main(){double x,y;cout<<”Input x:”;cin>>x;if(x<3.0)y=(x-2)*x;elseif(x>=-3.0&&x<=3.0) y=x;else y=x-2;cout<<”x=”<<x<<”,”<<”y=”<<y<<endl;}执行该程序后,显示如下信息:(分别输入3.2,2,-5) Input x:3.2↙输出结果如下:x=3.2,y=1.2Input x:2↙输出结果如下:x=2,y=2Input x:-5↙输出结果如下:x=-5,y=35该程序中使用了if-else if-else语句,用来实现三路分支。

面向对象的c++程序设计第六版课后习题答案第十章

面向对象的c++程序设计第六版课后习题答案第十章

面向对象的C++程序设计第六版课后习题答案第十章(总28页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--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 arrays 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 average;char grade;};void input(StudentRecord& student);void computeGrade(StudentRecord& student);void output(const StudentRecord student);int main(){StudentRecord student[CLASS_SIZE];for(int i = 0; i < CLASS_SIZE; i++)input(student[i]);<< "These are 100 point tests\n";cin >> >> ;cout << << " " <<<< endl << endl;}void computeGrade(StudentRecord& student) {n";abort();}= letterGrade[index];}void output(const StudentRecord student){cout << "The record for student number: " << << endl<< "The quiz grades are: "<< << " " <<<< endl<< "The midterm and exam grades are: "<< << " " <<<< endl<< "The numeric average is: " <<<< endl<< "and the letter 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 are 100 point tests 90 95enter the student number: 2enter two 10 point quizes9 8enter the midterm and final exam grades. These are 100 point tests 90 80enter the student number: 3enter two 10 point quizes7 8enter the midterm and final exam grades. These are 100 point tests 70 80enter the student number: 4enter two 10 point quizes5 8enter the midterm and final exam grades. These are 100 point tests 50 70enter the student number: 5enter two 10 point quizes4 0enter the midterm and final exam grades. These are 100 point tests 40 35The record for student number: 1The quiz grades are: 7 10The midterm and 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 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 midterm 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 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 differentcapitalization 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 so that theinterface 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 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 double)2) to take dollars and cents (int objects) from the internal representation and generate the external information.interest rate is a double (decimal) fraction ratherterm is stored the same#include <iostream>using namespace std;class CDAccount{public:CDAccount();CDAccount(double bal, double 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 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 based on the month numberan input function to set the month based on a three-character input an 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 for the streamData store 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 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:#include <fstream>Month();Month nextMonth(); This access member added forNot neede in this problemint Month::monthNumber(){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 == 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 << "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. Exiting\n"; exit(1);}void error(int n){cout << endl << n << " is not a month number. Exiting" << endl; exit(1);}void Month::getMonthByNumber(istream& in){in >> mnth;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', 'n');( cout ); cout << " ";(cout); cout << endl;m = Month( 'f', 'e', 'b');( cout ); cout << " ";(cout); cout << endl;m = Month( 'm', 'a', 'r');( cout ); cout << " ";(cout); 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');( cout ); cout << " ";(cout); cout << endl;m = Month( 'j', 'u', 'l');( cout ); cout << " ";(cout); cout << endl;m = Month( 'a', 'u', 'g');( cout ); cout << " ";(cout); cout << 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 ); 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);( 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<< "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 nextMonth member" << endl;cout << "current month ";(cout); cout << endl;cout << "next month ";().outputMonthNumber(cout); cout << " ";().outputMonthName(cout); cout << endl;cout << endl << "new Month created " << 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(char, 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 generate 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 three characters.8. Rewrite program from DisplayRewrite 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 written to a file. Input isstill from keyboard. Only the output is sent to a file.I have marked the start and endThis#include ""#include <fstream>#include <cstdlib >#include <cctype>using namespace std;class DayOfYear{public:void input(); void set(int newMonth, int newDay);int getMonth(); .12 = Decint 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 ";outStream << ". Bach's birthday is ";(cout);cout << endl;(outStream);outStream << endl;if ( () == ()&& () == () ){cout << "Happy Birthday Johann Sebastian!" << endl;outStream << "Happy Birthday Johann Sebastian!" << 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 the 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$ catToday'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 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$ catToday's date is Mar, 21. Bach's birthday is Mar, 21Happy Birthday Johann Sebastian!17:37:35:~/AW$9.“The Little Red Grocery Store Counter”One might start with the solution to #4 in solving this one.The class counter should provide:A default constructor. For example, Counter(9999); provides acounter that can count up to9999 and displays 0.A member function, void reset() that returns count to 0A 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 dollars and tens of dollars.Provide keys for incrementing cents, dimes, dollars and tens of dollars. Suggestion: asdfo: a for cents, followed by 1-9s for dimes, followed by 1-9d for dollars, followed by 1-9f for tens of dollars, followed by 1-9 Followed by pressing the return key in each case.Adding 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 useless, 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 followed by a digit 1-9:\n" << "Enter a for units\n"<< " s for tens\n"<< " d for hundreds\n"<< " f for thousands\n"<< " o to inquire about overflow\n"<< "Q or q at any time to quit.\n";cin >> ch;Quitting\n";return 0;}if(ch == 'o'){ cout << "Overflow test requested\n";if()){cout << "OVERFLOW HAS OCCURRED. RESULTS "<< "ARE NOT RELIABLE. Press Q to quit.\n"; }pause();continue; n";pause();continue; }cin >> j;default: cout << "Program should never get here\n" << "Fix program\n";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 Counter::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::overflow(){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 divide 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.”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 functions, 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);(100);cout << "For your gas guzzler:" << endl;cout << "After 100 miles, " << () <<" gallons used." << endl;(50);cout << "After another 50 miles, " << () <<" gallons used." << endl;return 0;}2. Outline of Topics in the ChapterStructuresStructures for Diverse DataStructures as Function ArgumentsInitializing StructureClassesDefining Classes and Member FunctionsPublic and Private MembersSummary of Some Properties of ClassesConstructors for InitializationAbstract Data TypesClasses to 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 provided on how to transform the solution. Prior to this chapter, we have seen the words class and object. We have seen examples of classes and objects, but we have not seen the tools to define classes. That is the subject matter of this chapter.Structures (keyword: struct)Historical note: The name struct in C++ is provided primarily for backward compatibility with ANSI C. (Every pro-gram in Kernighan and Ritchie, The C Programming Language, second edition, is a correct C++ program. In fact, the authors checked the code while writing that bookusing an early C++ compiler.) The author points out that two identifiers that are declared with the same structure type may be assigned, where member wise assignment1 occurs. The critical point here is that the two structure identifiers be declared with the same struct tag. In the example that follows, the types are indistinguishable from the member structure within the struct. However, C++ uses name equivalence for types, so the compiler looks at the tags in the declarations rather than the structure to determine whether one struct variable may be assigned to another.Example:struct A{int x;int y;};struct B{int x;int y;};1 Memberwise assignment is made from the r-value member to the l-value member in the corresponding position. The two objects are defined with the same structure tag so members in corresponding positions will have the same type. We will see that different classes can have differing assignment definitions. The assignment that occurs is thetype defined for the type of the member. We will see in a later chapter that thisdefault assignment mechanism is the only one the compiler can always know how to do,and may well not be what the programmer should use.A u;B v;u = v; With early compilers, and some current compilers, this pitfall generates particularly uninformative error messages. It will be quite helpful for the student to write several examples in which the closing semicolon in a structure definition is deliberately omitted.For example, the Gnu C++ compiler, g++, advises that there is a semicolon missing after the class definition. This is one of the few understandable messages about this error. I have listed other, less comprehensible,error messages in comments in this example.class A{public: A();private: int i;int It is easy to confuse compilers.Programming Tip: Hierarchical StructuresIt is worth pointing out that the name spaces for hierarchical (or nested) structures are also separate. The same names can be used in thecontaining struct as are used in the structure member. The same names can be used in two structures members at the same level.Example: Name space and hierarchical structure initializationOutput:= 1 = 2= 3 = 4 = 4 = 5This is, of course, a "horrible example", designed to show a worst case. One would almost never use the same identifiers in two structures whileusing a struct object as a member of another as we do here. (This is known as composing structures.) However, this does serve to illustratethe idea that the name spaces for two structures are separate. (This is also true for classes as well.) If there is a need to duplicate a member name, this won't break the program.Incidentally, the initialization for composition of structures is illustrated in the above example. This initialization also works when the inside braces are omitted. Some compilers will warn about a lack of grouping. Borland's BCC 32 version gives no warning, but the GNU C++,g++ , gives this warning:warning: aggregate has a partly bracketed initializerClassesDefining Classes and Member FunctionsHere are some remarks on the scope resolution operator, ::, from the text. The name of a class (and a struct, for that matter) with the {}; definesa scope within which variables and functions can be defined. They are not accessible outside the scope without qualification by the object name and a dot operator. Member functions are defined on behalf of a particular class, to be used by any object declared to be of that class, again, only with qualification by being preceded by the object name and the dot operator.To define a function whose prototype is given in a class, we have to specify the scope of that class within which the function is to be defined. This is done with the class tag and scope resolution operator:To say:returnTypeName classTag::funcMemberName(argumentList){The data members belong to a particular object, and function members must be called on behalf of this object. Hence, the object must be specified. On ConstructorsThe text points out that this line of codeBankAccount account2();will give trouble. The problem with this line is that this appears to invoke the default constructor. The student will reason that there is a correspondence between calling functions that have arguments with invoking constructors that have arguments, so there should be a correspondence between calling functions with no arguments and invoking constructors with no arguments. The trouble is that this line actually declares account2 to be a function that takes no arguments and returns a BankAccount object. If this is intended, and the use of account2 later is consistent with this declaration, things are fine. At the first year level, this is unlikely.Suppose this isn't what is intended. Then the third line will compile, without an error, but errors are generated later that are almostincomprehensible, to the student, at least.. Here is an example of this error and the error messages that result.int main(){A w();cout << () << endl;w = A(1);cout << () << endl;}/*g++ error messages:21: request for member `X' in `w', which is of non-aggregatetype `A ()()'22: assignment of function `w()'22: conversion from `A' to non-scalar type `A ()()' requested23: request for member `X' in `w', which is of non-aggregatetype `A ()()'Borland C++ for Win32 error messages:21: Structure required on left side of . or .* in function main()22: Lvalue required in function main()23: Structure required on left side of . or .* in function main()*/Of course, once you learn to read this syntax, this is easy to interpret.I have few students who understand that well at this point in the course.Students need to write code with known errors to be able to recognize the errors made inadvertently based on the error messages.A note on initialization. The notation:x(0) and :x(X) in the constructor definitions,A::A():x(0){}A::A(int X):x(X) {}is an alternate mechanism for constructor to initialize the private variables in the class. We could just as easily have written A::A(){x = 0;}andA::A(int X){x = X;}except that when we have private data members that are of reference type or are const we must use this initialization variant, there is no other way to do the initialization. This is why I use this notation consistently. At this point, there is no compelling reason to use this notation, and it is well to have several ways to do the task. If you intend to use this C++ idiom, it will be well to assign Appendix 7 from the text for reading. It is worth repeating an earlier remark: The methodused in the text is clear, intuitive and simple, and it works for the cases the student will see in this course. However, I expect my students to be aware of both techniques, hence I present this idea here.Writing and Debugging Suggestions for ClassesI recommend to my students that they plan before coding. I emphasize that the sooner coding begins, the longer the time it takes to arrive at a correct solution to any problem worthy of the name. When coding begins, first create the class definition, without any of the member function definitions. Add the dummy main function int main(){} to the class, be sure the suffix is .cc, .cxx, .cpp, . what your compiler requires, then compile. It is faster to compile with the no code generation option (g++ -fsyntax-only , or equivalent for your compiler. ) This will enable finding syntax errors in the class definition prior to attempting to define the members, and will prevent these errors from adverselyaffecting the member functions.Further, I recommend that the student code class member implementations one or at most a very few at a time. then compile. This constrains the location of the errors.“Code a little then test a lot. Constrain the places where errors can occur.”After each chunk of members is written, test that chunk, as independently of each other as possible. Code a little, then test. Constrain the places where errors can occur. By the time the class is implemented and tested,。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter15INHERITANCE1.Solutions to and Remarks on Selected Programming Problems1.Derive class Administrator from class SalariedEmployeePlease note an error in the statement of Programming Project1:In the requirement for a member function called"print"which the problem says"...output the programmer's data to the screen."This should read"...output the administrator's data to the screen."Remarks:Ideally the member functions in the base class Employee that are going to be declared in derived classes should be declared"pure virtual"where the body{...}is replaced by=0;. This results in the compiler forcing any directly derived function to define a member with this signature,which,presumably is better suited than any base class member function will be.Print check may well be different for each derived class.The member function void give_raise(double)could be different as well.Regarding the function that reads the administrator's data,note that a new administrator's data will be entered in response to the base class Employee and derive class SalariedEmployee inquiries,then the administrator class function will make inquiry.My design and implementation follow:Title:Derive class AdministratorWrite a program using classes from Display15.1-15.4Define class Administrator which derives publicly from class SalariedEmployee. Explain why there is a need to change private:to protected:Answer:To allow the member functions inherited class member to see these data members.Additional protected members required are:string titleadministrator's title(CEO,Director etc.)string responsibility(production,accounting,personnel) string supervisor(name of immediate supervisor)double annual_salary(if not already added in the self test exercise)Additional public members required are:A function to change name of immediate supervisorvoid change_supervisor(string new_super);A function for reading all of a new administrator's data from the keyboard.Note that the data inherited from class Employee will already be fetched by required base class constructors.class constructors.void get_admin_data();function to output administrator's data to the screenvoid print();a function to print a check with appropriate notations on the checkvoid print_check()//file:ch15p1.h//This is the INTERFACE for class Administrator which//inherits from class Employee and class SalariedEmployee#ifndef ADMINISTRATOR_H#define ADMINISTRATOR_H#include"employee.h"//from Display15.1 namespace employeessavitch{class Administrator:public SalariedEmployee{public:Administrator();Administrator(string aTitle,string aResponsibilty,string aSupervisor);//change name of immediate supervisorvoid change_supervisor(string new_super);//Read a new administrator's data from the keyboard.void get_admin_data();//outputs administrator's data to the screenvoid print();//prints a check with appropriate notations on the checkvoid print_check();void give_raise(double amount);protected:string title;//administrator's title//(CEO,Director,Vice President)string responsibility;//production,accounting, personnelstring supervisor;//name of immediate supervisor long double annual_salary;//if not added in the self//test exercise};}#endif//File://Chapter15Programming Project1//Implementation for the Administrator derived class#include"employee.h"//display15.2#include"ch15p1.h"//Previous header file#include<iostream>namespace employeesavitch{voidAdministrator::give_raise(double amount){annual_salary+=amount;}Administrator::Administrator():SalariedEmployee(){using namespace std;cout<<"\nAdministrative Employee data"<<"is being entered:\n\n";get_admin_data();}Administrator::Administrator(string aTitle,string aResponsibilty,string aSupervisor):SalariedEmployee(),title(aTitle),responsibility(aResponsibilty),supervisor(aSupervisor){//deliberately empty}//change name of immediate supervisorvoid Administrator::change_supervisor(string new_super) {supervisor=new_super;}//Reading all of a new administrator's data from the//keyboard.void Administrator::get_admin_data(){using namespace std;cout<<"Enter title,followed by return:\n";getline(cin,title);cout<<"\nEnter area of responsibility"<<"followed by return:\n";getline(cin,responsibility);cout<<"\nEnter supervisor's name,"<<"followed by return:\n";getline(cin,supervisor);cout<<"\nEnter salary followed by return:\n";cin>>annual_salary;}//outputs administrator's data to the screenvoid Administrator::print(){using namespace std;cout<<"\n\nprinting data\n";cout<<"Name:"<<name<<endl;cout<<"Annual Salary:$"<<annual_salary<<endl; cout<<"Social Security Number:"<<ssn<<endl; cout<<"Title:";cout<<title<<endl;cout<<"Responsibility:";cout<<responsibility<<endl;cout<<"supervisor:";cout<<supervisor<<endl;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);cout<<"Annual Salary:";cout<<annual_salary<<endl;}//prints a check with appropriate notations on the check void Administrator::print_check(){using namespace std;long double monthly_pay=annual_salary/12;cout<<"\n__________________________________________________\n"; cout<<"Pay to the order of"<<name<<endl;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);cout<<"The sum of$"<<monthly_pay<<"Dollars\n";cout<<"_________________________________________________\n";cout<<"Check Stub NOT NEGOTIABLE\n";cout<<"Employee Number:"<<ssn<<endl;cout<<"Administrative Employee.\n";cout<<"_________________________________________________\n"; }}//end namespace employeesavitch2.Add Temporary,Administrative,Permenant etc classifications to15.1…No solution is provided for this problem.3.Derive class Doctor from SalariedEmployeeNo solution is provided for this problem.4.Create a base class vehicleNo solution is provided for this problem.5.Define classes Patient and BillingNo solution is provided for this problem.6.No Solution Provided.7.Implement a graphics SystemImplement a graphics System that has classes for various figures:rectangles,squares, triangles,circles,etc.A rectangle has data members height,width,and center point.A square has center point and an edge.A circle has data members center and radius.The several specific shape classes are derived from a common class,Figure. Implement only Rectangle and Triangle classes.Derive them from Figure. Each class has stubs for erase and draw.The class Figure has member function center that calls erase and draw.The functions erase and draw are only stubs,consequently center does little but call erase and draw.Add a message to center announcing that it is being called.There are3parts:a)Write the class definitions using no virtual pile and test.b)Make the base class member functions pile and test.c)Explain the differences.Use the following main function:#include<iostream>#include"figure.h"#include"rectangle.h"#include"triangle.h"using std::cout;int main(){Triangle tri;tri.draw();cout<<"\nDerived class Triangle object calling"<<"center().\n";tri.center();Rectangle rect;rect.draw();cout<<"\nDerived class Rectangle object calling"<<"center().\n";rect.center();return0;}Solution:I have used no member variables,as they serve no function in this part of the exercise.//figure.h#include<iostream>using namespace std;#ifndef PROTECT_FIGURE_H#define PROTECT_FIGURE_Hclass Figure{public://virtual//Uncomment to make erase()a virtual function void erase();//virtual//Uncomment to make draw()a virtual function void draw();void center(){cout<<"member function center called"<<endl;erase();draw();}};#endif//File:figure.cpp#include"figure.h"void Figure::erase(){cout<<"Figure::erase()"<<endl; }void Figure::draw(){cout<<"Figure::draw()"<<endl; }//end of file figure.cpp//rectangle.h#include<iostream>#include"figure.h"using namespace std;class Rectangle:public Figure{public:void erase();void draw();};void Rectangle::erase(){cout<<"Rectangle::erase()"<<endl; }void Rectangle::draw(){cout<<"Rectangle::draw()"<<endl; }//triangle.h#include<iostream>#include"figure.h"using namespace std;class Triangle:public Figure{public:void draw();void erase();};void Triangle::draw(){cout<<"Triangle::draw()"<<endl; }void Triangle::erase(){cout<<"Triangle::erase()"<<endl;}//ch13p1App.cpp#include<iostream>#include"figure.h"#include"rectangle.h"#include"triangle.h"using std::cout;int main(){Triangle tri;tri.draw();cout<<"\nIn main,Derived class Triangle object calling"<<"center().\n";tri.center();Rectangle rect;rect.draw();cout<<"\nIn main,Derived class Rectangle object calling"<<"center().\n";rect.center();return0;}A trial run follows:With NON virtual draw()and erase()Triangle::draw()In main,Derived class Triangle object calling center(). member function center calledFigure::erase()Figure::draw()Rectangle::draw()In main,Derived class Rectangle object calling center(). member function center calledFigure::erase()Figure::draw()With virtual draw()and erase():Triangle::draw()In main,Derived class Triangle object calling center(). member function center calledTriangle::erase()Triangle::draw()Rectangle::draw()Explanation of differenceThe differences are due solely to the presence or absence of the keyword virtual in the base class figure.8.Flesh out Problem7Give new definitions and member functions for Figure::center,Figure::draw, Figure::erase,Triangle::draw,Triangle::erase, Rectangle::draw,Rectangle::erase,so that the draw functions actually draw figures on the screen using asterisks(*).For the erase function,clear the screen.No solution to this part is provided.9.No Solution Provided.10.//****************************************************************////Ch15Proj10.cpp////This program uses inheritance to simulate retrieving the contents //of a RFID shipping container and a manual shipping container.//****************************************************************#include<iostream>#include<vector>#include<string>#include<sstream>using namespace std;//*************************Begin ShippingContainer Classclass ShippingContainer{public:ShippingContainer();ShippingContainer(int newID);int getID();void setID(int newID);virtual string getManifest();private:int id;};//======================//ShippingContainer::ShippingContainer//Constructors//======================ShippingContainer::ShippingContainer(){id=-1;}ShippingContainer::ShippingContainer(int newID){id=newID;}//======================//ShippingContainer::getID//Returns the ID number//======================int ShippingContainer::getID(){return id;}//======================//ShippingContainer::setID//Sets the ID number//======================void ShippingContainer::setID(int newID){id=newID;}//======================//ShippingContainer::getManifest//Returns empty contents//======================string ShippingContainer::getManifest(){return"";}//*************************Begin ManualShippingContainer Classclass ManualShippingContainer:public ShippingContainer{public:ManualShippingContainer(int newID);void setManifest(string s);virtual string getManifest();private:string contents;};//======================//ManualShippingContainer::ManualShippingContainer//Constructor//====================== ManualShippingContainer::ManualShippingContainer(int newID): ShippingContainer(newID){}//======================//ManualShippingContainer::setManifest//Sets the manifest for this container//======================void ManualShippingContainer::setManifest(string s){contents=s;}//======================//ManualShippingContainer::getManifest//Returns the manifest for this container//======================string ManualShippingContainer::getManifest(){return contents;}//*************************Begin RFIDShippingContainer Classclass RFIDShippingContainer:public ShippingContainer{public:RFIDShippingContainer(int newID);void add(string s);virtual string getManifest();private:vector<string>contents;vector<int>count;int search(string s);};//======================//RFIDShippingContainer::RFIDShippingContainer//Constructor//======================RFIDShippingContainer::RFIDShippingContainer(int newID):ShippingContainer(newID){}//======================//RFIDShippingContainer::search//Search the vector for duplicates and if found//returns the index,or-1if not found//======================int RFIDShippingContainer::search(string s){int i;for(i=0;i<contents.size();i++){if(contents[i]==s)return i;}return-1;}//======================//RFIDShippingContainer::add//Adds a new string to the manifest vector.//======================void RFIDShippingContainer::add(string s){int i;i=search(s);if(i==-1){contents.push_back(s);//Add itemcount.push_back(1);//One occurrence of this item }else{count[i]++;//Add to occurrences of this item }}//======================//RFIDShippingContainer::getManifest//Returns the manifest for this container//by scanning through the vector//======================string RFIDShippingContainer::getManifest(){string s="";int i;for(i=0;i<contents.size();i++){//Convert number to string using stringstreamstringstream converter;converter<<count[i];s+=converter.str()+""+contents[i]+".";}return s;}//======================//main function//======================int main(){//Variable declarations with test data ShippingContainer*containers[6]; ManualShippingContainer m1(100),m2(200),m3(300); RFIDShippingContainer r1(400),r2(500),r3(600);m1.setManifest("1000diapers");m2.setManifest("1000candy bars.500toilet paper.");m3.setManifest("500books.");r1.add("apples");r1.add("apples");r1.add("cookies");r2.add("pineapple");r2.add("pears");r2.add("pineapple");r2.add("pears");r3.add("chocolate bars");r3.add("chocolate bars");r3.add("chocolate bars");//Store containers in the arraycontainers[0]=&m1;containers[1]=&m2;containers[2]=&m3;containers[3]=&r1;containers[4]=&r2;containers[5]=&r3;//Loop to output contents of the containersfor(int i=0;i<6;i++){cout<<"Container"<<containers[i]->getID()<<"contains"<<containers[i]->getManifest()<<endl; }return0;}11.//**************************************************************** ////Ch15Proj11.cpp////This program simulates a2D world with predators and prey.//The predators(doodlebugs)and prey(ants)inherit from the//Organism class that keeps track of basic information about each //critter(time ticks since last bred,position in the world).////The2D world is implemented as a separate class,World,//that contains a2D array of pointers to type Organism.////Normally the classes would be defined in separate files,but//they are all included here for ease of use with CodeMate.//****************************************************************#include<iostream>#include<string>#include<vector>#include<cstdlib>#include<time.h>using namespace std;const int WORLDSIZE=20;const int INITIALANTS=100;const int INITIALBUGS=5;const int DOODLEBUG=1;const int ANT=2;const int ANTBREED=3;const int DOODLEBREED=8;const int DOODLESTARVE=3;//Forward declaration of Organism classes so we can reference it//in the World classclass Organism;class Doodlebug;class Ant;//==========================================//The World class stores data about the world by creating a//WORLDSIZE by WORLDSIZE array of type Organism.//NULL indicates an empty spot,otherwise a valid object//indicates an ant or doodlebug.To determine which,//invoke the virtual function getType of Organism that should return //ANT if the class is of type ant,and DOODLEBUG otherwise.//==========================================class World{friend class Organism;//Allow Organism to access grid friend class Doodlebug;//Allow Organism to access grid friend class Ant;//Allow Organism to access grid public:World();~World();Organism*getAt(int x,int y);void setAt(int x,int y,Organism*org);void Display();void SimulateOneStep();private:Organism*grid[WORLDSIZE][WORLDSIZE];};//==========================================//Definition for the Organism base class.//Each organism has a reference back to//the World object so it can move itself//about in the world.//==========================================class Organism{friend class World;//Allow world to affect organism public:Organism();Organism(World*world,int x,int y);~Organism();virtual void breed()=0;//Whether or not to breedvirtual void move()=0;//Rules to move the crittervirtual int getType()=0;//Return if ant or doodlebugvirtual bool starve()=0;//Determine if organism starves protected:int x,y;//Position in the worldbool moved;//Bool to indicate if moved this turnint breedTicks;//Number of ticks since breeding World*world;};//======================//World constructor,destructor//These classes initialize the array and//releases any classes created when destroyed.//======================World::World(){//Initialize world to empty spacesint i,j;for(i=0;i<WORLDSIZE;i++){for(j=0;j<WORLDSIZE;j++){grid[i][j]=NULL;}}}World::~World(){//Release any allocated memoryint i,j;for(i=0;i<WORLDSIZE;i++){for(j=0;j<WORLDSIZE;j++){if(grid[i][j]!=NULL)delete(grid[i][j]);}}}//======================//getAt//Returns the entry stored in the grid array at x,y//======================Organism*World::getAt(int x,int y){if((x>=0)&&(x<WORLDSIZE)&&(y>=0)&&(y<WORLDSIZE)) return grid[x][y];return NULL;}//======================//setAt//Sets the entry at x,y to the//value passed in.Assumes that//someone else is keeping track of//references in case we overwrite something//that is not NULL(so we don't have a memory leak)//======================void World::setAt(int x,int y,Organism*org){if((x>=0)&&(x<WORLDSIZE)&&(y>=0)&&(y<WORLDSIZE)){grid[x][y]=org;}}//======================//Display//Displays the world in es o for ant,X for doodlebug. //======================void World::Display(){int i,j;cout<<endl<<endl;for(j=0;j<WORLDSIZE;j++){for(i=0;i<WORLDSIZE;i++){if(grid[i][j]==NULL)cout<<".";else if(grid[i][j]->getType()==ANT)cout<<"o";else cout<<"X";}cout<<endl;}}//======================//SimulateOneStep//This is the main routine that simulates one turn in the world.//First,a flag for each organism is used to indicate if it has moved. //This is because we iterate through the grid starting from the top//looking for an organism to move.If one moves down,we don't want//to move it again when we reach it.//First move doodlebugs,then ants,and if they are still alive then//we breed them.//======================void World::SimulateOneStep(){int i,j;//First reset all organisms to not movedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if(grid[i][j]!=NULL)grid[i][j]->moved=false;}//Loop through cells in order and move if it's a Doodlebugfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if((grid[i][j]!=NULL)&&(grid[i][j]->getType()==DOODLEBUG)){if(grid[i][j]->moved==false){grid[i][j]->moved=true;//Mark as movedgrid[i][j]->move();}}}//Loop through cells in order and move if it's an Antfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){if((grid[i][j]!=NULL)&&(grid[i][j]->getType()==ANT)){if(grid[i][j]->moved==false){grid[i][j]->moved=true;//Mark as movedgrid[i][j]->move();}}}//Loop through cells in order and check if we should breedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){//Kill off any doodlebugs that haven't eaten recentlyif((grid[i][j]!=NULL)&&(grid[i][j]->getType()==DOODLEBUG)){if(grid[i][j]->starve()){delete(grid[i][j]);grid[i][j]=NULL;}}}//Loop through cells in order and check if we should breedfor(i=0;i<WORLDSIZE;i++)for(j=0;j<WORLDSIZE;j++){//Only breed organisms that have moved,since//breeding places new organisms on the map we//don't want to try and breed thoseif((grid[i][j]!=NULL)&&(grid[i][j]->moved==true)){grid[i][j]->breed();}}}//======================//Organism Constructor//Sets a reference back to the World object.//======================Organism::Organism(){world=NULL;moved=false;breedTicks=0;x=0;y=0;}Organism::Organism(World*wrld,int x,int y){this->world=wrld;moved=false;breedTicks=0;this->x=x;this->y=y;wrld->setAt(x,y,this);}//======================//Organism destructor//No need to delete the world reference,//it will be destroyed elsewhere.//======================Organism::~Organism(){}//Start with the Ant classclass Ant:public Organism{friend class World;public:Ant();Ant(World*world,int x,int y);void breed();//Must define this since virtualvoid move();//Must define this since virtualint getType();//Must define this since virtualbool starve()//Return false,ant never starves{return false;}};//======================//Ant constructor//======================Ant::Ant():Organism(){}Ant::Ant(World*world,int x,int y):Organism(world,x,y) {}//======================//Ant Move//Look for an empty cell up,right,left,or down and//try to move there.//======================void Ant::move(){//Pick random direction to moveint dir=rand()%4;//Try to move up,if not at an edge and empty spotif(dir==0){if((y>0)&&(world->getAt(x,y-1)==NULL)){world->setAt(x,y-1,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);y--;}}//Try to move downelse if(dir==1){if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)==NULL)){world->setAt(x,y+1,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyy++;}}//Try to move leftelse if(dir==2){if((x>0)&&(world->getAt(x-1,y)==NULL)){world->setAt(x-1,y,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyx--;}}//Try to move rightelse{if((x<WORLDSIZE-1)&&(world->getAt(x+1,y)==NULL)){world->setAt(x+1,y,world->getAt(x,y));//Move to new spotworld->setAt(x,y,NULL);//Set current spot to emptyx++;}}}//======================//Ant getType//This virtual function is used so we can determine//what type of organism we are dealing with.//======================int Ant::getType(){return ANT;}//======================//Ant breed//Increment the tick count for breeding.//If it equals our threshold,then clone this ant either//above,right,left,or below the current one.//======================void Ant::breed(){breedTicks++;if(breedTicks==ANTBREED){breedTicks=0;//Try to make a new ant either above,left,right,or downif((y>0)&&(world->getAt(x,y-1)==NULL)){Ant*newAnt=new Ant(world,x,y-1);}else if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)==NULL)){Ant*newAnt=new Ant(world,x,y+1);}else if((x>0)&&(world->getAt(x-1,y)==NULL)){Ant*newAnt=new Ant(world,x-1,y);}else if((x<WORLDSIZE-1)&&(world->getAt(x+1,y)==NULL)){Ant*newAnt=new Ant(world,x+1,y);}}}//*****************************************************//Now define Doodlebug Class//*****************************************************class Doodlebug:public Organism{friend class World;public:Doodlebug();Doodlebug(World*world,int x,int y);void breed();//Must define this since virtualvoid move();//Must define this since virtualint getType();//Must define this since virtualbool starve();//Check if a doodlebug starves to deathprivate:int starveTicks;//Number of moves before starving};//======================//Doodlebug constructor//======================Doodlebug::Doodlebug():Organism(){starveTicks=0;}Doodlebug::Doodlebug(World*world,int x,int y):Organism(world,x,y) {starveTicks=0;}//======================//Doodlebug move//Look up,down,left or right for a bug.If one is found,move there //and eat it,resetting the starveTicks counter.//======================void Doodlebug::move(){//Look in each direction and if a bug is found move there//and eat it.if((y>0)&&(world->getAt(x,y-1)!=NULL)&&(world->getAt(x,y-1)->getType()==ANT)){delete(world->grid[x][y-1]);//Kill antworld->grid[x][y-1]=this;//Move to spotworld->setAt(x,y,NULL);starveTicks=0;//Reset hungery--;return;}else if((y<WORLDSIZE-1)&&(world->getAt(x,y+1)!=NULL)&&(world->getAt(x,y+1)->getType()==ANT)){delete(world->grid[x][y+1]);//Kill antworld->grid[x][y+1]=this;//Move to spotworld->setAt(x,y,NULL);starveTicks=0;//Reset hungery++;return;}else if((x>0)&&(world->getAt(x-1,y)!=NULL)&&(world->getAt(x-1,y)->getType()==ANT)){delete(world->grid[x-1][y]);//Kill antworld->grid[x-1][y]=this;//Move to spot。

相关文档
最新文档