C++Primer Plus第十章对象与类课后习题

合集下载

C++第10章习题参考答案

C++第10章习题参考答案

四、综合题3 综合题3
答案: 答案: 调用d.vf2() 是错误的:对象将直接调用本类函数,但是 是错误的:对象将直接调用本类函数,但是DD 调用 类的vf2 函数需要一个参数。 函数需要一个参数。 类的 调用dp->vf2() 是错误的:由于 是错误的:由于DD 类的 类的vf2 函数和基类 函数和基类vf2 调用 的参数不一致,虚函数关系不成立,调用将指向DD 类 的参数不一致,虚函数关系不成立,调用将指向 函数,仍然出现参数的不一致。 的vf2 函数,仍然出现参数的不一致。 这两个语句注释掉后,运行的结果是: 这两个语句注释掉后,运行的结果是: DD::vf1 被调用 BB::vf2 被调用 EE::vf4 被调用 EE::vf3 被调用 联编的方式分别是:动态联编、静态联编、动态联编、 联编的方式分别是:动态联编、静态联编、动态联编、动 态联编。 态联编。
四、综合题2 综合题2
class Circle : public Shape { public: public: Circle( int = 0, int = 0, double = 0.0 ); const; virtual double getArea() const; const; void print() const; private: private: x,y; int x,y; radius; double radius; }; class Rectangle : public Shape { public: public: Rectangle( int = 0, int = 0); virtual double getArea() const const; void print() const; private: private: int a,b; a,b; };

C++ primer plus(第6版)中文版编程练习答案第10章

C++ primer plus(第6版)中文版编程练习答案第10章

第10章1、//Customs.h#include <stdio.h>#include <tchar.h>#include <string>#include <iostream>using namespace std;class Customs{private:string name;string accnum;double balance;public:Customs(const string &client, const string &num, double bal = 0.0);~Customs();void show()const;bool deposit(double cash);bool withdraw(double cash);};//Customs.cpp#include "Customs.h"Customs::Customs(const string &client,const string &num, double bal) {accnum = num;name = client;balance = bal;}Customs::~Customs(){}bool Customs::deposit(double cash){if (cash <= 0){cout << "Deposit must greater than zero\n";return false;}else{cout << "Custom deposits $" << cash << " dolars.\n";balance += cash;return true;}}bool Customs::withdraw(double cash){if (cash <= 0 || (balance - cash) < 0){cout << "Withdraw money error, must less than balance and greater than zero\n";return false;}else{cout << "Custom withdraws $" << cash << " dolars\n";balance -= cash;return true;}}void Customs::show()const{cout << "Account custom's name is " << name << endl;cout << "Account number is " << accnum << endl;cout << "Custom's balance is " << balance << endl;}//main.cpp#include "Customs.h"int main(){double input, output;char ch;Customs custom=Customs("Jacky","Jc",3000.32);custom.show();cout << "Please enter A to deposit balance ,\n"<< "P to withdraw balance, or Q to quit.: ";while (cin >> ch && toupper(ch)!='Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case'A':case'a':cout << "Enter a account number to deposit: ";cin >> input;if (!custom.deposit(input))cout << "Add error\n";elsecout << "Add success\n";break;case'P':case'p':cout << "Enter a account number to withdraw: ";cin >> output;if (!custom.withdraw(output))cout << "Withdraw error\n";elsecout << "Withdraw success\n";break;}custom.show();cout << "Please enter A to deposit balance ,\n"<< "P to withdraw balance, or Q to quit: ";}cout << "Bye\n";cin.get();cin.get();return 0;}2、//person.h#ifndef PERSON_H_#define PERSON_H_#include <iostream>#include <stdio.h>#include <tchar.h>#include <string>using namespace std;class Person{private:static const int Person::LIMIT = 25;string lname;char fname[LIMIT];public:Person(){ lname = ""; fname[0] = '\0'; }Person(const string &ln, const char *fn = "Heyyou");void Show()const;void FormalShow()const;};#endif//person.cpp#include "person.h"Person::Person(const string &ln, const char *fn){lname = ln;strncpy_s(fname, fn, LIMIT);fname[LIMIT] = '\0';}void Person::Show()const{cout << fname << " " << lname;}void Person::FormalShow()const{cout << lname << ", " << fname; }//usePerson.cpp#include "person.h"int main(){Person one;Person two("Smythecraft");Person three("Dimwiddy", "Sam");one.Show();cout << endl;one.FormalShow();cout << endl;two.Show();cout << endl;two.FormalShow();cout << endl;three.Show();cout << endl;three.FormalShow();cout << endl;cin.get();return 0;}3、//golf.h#ifndef GOLF_H_#define GOLF_H_#include <iostream>#include <string>using namespace std;class golf{private:static const int Len = 40;char fullname[Len];int handicap;public:golf();golf(const char *name, int hc = 0);golf(golf &g);~golf();void handicapf(int hc);void show()const;};#endif//golf.cpp#include "golf.h"golf::golf(){}golf::golf(const char *name, int hc){strncpy_s(fullname, name, Len);fullname[Len] = '\0';handicap = hc;}golf::golf(golf &g){strncpy_s(this->fullname, g.fullname, Len);this->handicap = g.handicap;}golf::~golf(){}void golf::handicapf( int hc){handicap = hc;}void golf::show()const{cout << fullname << ", " << handicap << endl; }//main.cpp#include "golf.h"int main(){char name[40] = "\0";int no;cout << "Enter a name: ";cin.getline(name, 40);cout << "Enter a level: ";cin >> no;golf ann(name, no);ann.show();golf andy = golf(ann);andy.show();cin.get();cin.get();return 0;}4、//Sales.h#ifndef SALE_H_#define SALE_H_#include <iostream>#include <string>using namespace std;namespace SALES{class Sales{private:static const int QUARTERS = 4;double sales[QUARTERS];double average;double max;double min;public:Sales();Sales(const double *ar);Sales(Sales &s);~Sales();void showSales()const;};}#endif//Sales.cpp#include "Sales.h"using namespace SALES;Sales::Sales(){sales[QUARTERS] = '\0';average = 0.0;max = 0.0;min = 0.0;}Sales::Sales(const double *ar){double sum=0.0;for (int i = 0; i < QUARTERS; i++){sales[i] = ar[i];sum += sales[i];}average = sum / QUARTERS;max = sales[0];for (int i = 0; i < QUARTERS-1; i++){if (sales[i] < sales[i + 1])max = sales[i + 1];}min = sales[0];for (int i = 0; i < QUARTERS-1; i++){if (sales[i] > sales[i + 1])min = sales[i + 1];}}Sales::Sales(Sales &s){for (int i = 0; i < QUARTERS; i++)this->sales[i] = s.sales[i];this->average = s.average;this->max = s.max;this->min = s.min;}Sales::~Sales(){}void Sales::showSales()const{cout << "The sales number is \n";for (int i = 0; i < QUARTERS; i++){cout << sales[i] << " ";}cout << endl;cout << "The sales average is " << average << endl;cout << "The sales max is " << max << endl;cout << "The sales min is " << min << endl;}//main.cpp#include "Sales.h"using namespace SALES;int main(){double nums[4];cout << "Please enter four numbers: \n";for (int i = 0; i < 4; i++)cin >> nums[i];Sales sn(nums);sn.showSales();Sales sn1(sn);sn1.showSales();cin.get();cin.get();return 0;}5、//stack.h#ifndef STACK_H_#define STACK_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;struct customer{char fullname[35];double payment;};typedef struct customer Item;class Stack{private:enum{ MAX = 10 };Item items[MAX];double sum;int top;public:Stack();~Stack();bool isempty()const;bool isfull()const;bool push(const Item &item);bool pop(Item &item);};#endif#include "stack.h"Stack::Stack(){top = 0;sum = 0.0;}Stack::~Stack(){}bool Stack::isempty()const{return top == 0;}bool Stack::isfull()const{return top == MAX;}bool Stack::push(const Item &item) {if (top < MAX){items[top++] = item;return true;}elsereturn false;}bool Stack::pop(Item &item){if (top > 0){item = items[--top];sum += item.payment;cout << sum << endl;return true;}return false;}//main.cpp#include "stack.h"int main(){Stack st;char ch;Item cs;cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";while (cin >> ch && toupper(ch) != 'Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case 'A':case 'a':cout << "Enter a PO number to add: ";cin >> cs.fullname;cin >> cs.payment;if (st.isfull())cout << "stack already full\n";elsest.push(cs);break;case 'P':case 'p':if (st.isempty())cout << "stack already empty\n";else{st.pop(cs);cout << "PO #" << cs.fullname << "popped\n";}break;}cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";}cout << "Bye\n";cin.get();cin.get();return 0;}6、//Move.h#ifndef MOVE_H_#define MOVE_H_#include <stdio.h>#include <iostream>#include <string>using namespace std;class Move{private:double x;double y;public:Move(double a = 0, double b = 0);void showmove()const;Move add(const Move &m)const;void reset(double a = 0, double b = 0);};#endif//Move.cpp#include "Move.h"Move::Move(double a, double b){x = a;y = b;}void Move::showmove()const{cout << "x = " << x << endl;cout << "y = " << y << endl;}Move Move::add(const Move &m)const {Move xy_add;xy_add.x = m.x + this->x;xy_add.y = m.y + this->y;return xy_add;}void Move::reset(double a, double b) {x = a;y = b;}//main.cpp#include "Move.h"int main(){Move xy0(1, 1);xy0.showmove();Move xy1;xy1 = Move(2, 2);xy1.showmove();xy1 = xy1.add(xy0);xy1.showmove();xy1.reset(2.5, 2.5);xy1.showmove();cin.get();return 0;}7、//plorg.h#ifndef PLORG_H_#define PLORG_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;class plorg{private:static const int len = 19;char fullname[len];int CI;public:plorg(const char *name = "Plorga", int ci = 50);~plorg();void p_fix(int ci);void show()const;};#endif//plorg.cpp#include "plorg.h"plorg::plorg(const char *name, int ci){strncpy_s(fullname, name, len);CI = ci;}plorg::~plorg(){}void plorg::p_fix(int ci){CI = ci;}void plorg::show()const{cout << fullname << ", " << CI << endl; }//main.cpp#include "plorg.h"int main(){plorg pl;pl.show();pl.p_fix(32);pl.show();plorg pll("Plorgb", 27);pll.show();pll.p_fix(32);pll.show();cin.get();return 0;}8、//list.h#ifndef LIST_H_#define LIST_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;typedef unsigned long Item;class List{private:enum { MAX = 10 };Item items[MAX];int head;int rear;public:List();bool isempty()const;bool isfull()const;bool add(const Item &item);bool cut(Item &item);void show()const;void visit(void(*pf)(Item &)); };#endif//list.cpp#include "list.h"List::List(){head = 0;rear = 0;}bool List::isempty()const{return rear == head;}bool List::isfull()const{return rear - head == MAX; }bool List::add(const Item &item) {if (rear < MAX){items[rear++] = item;return true;}elsereturn false;}bool List::cut(Item &item){if (rear < MAX){item = items[--rear];return true;}elsereturn false;}void List::show()const{for (int i = head; i < rear; i++)cout << items[i] << ", ";cout << endl;}void List::visit(void(*pf)(Item &)){for (int i = 0; i < rear; i++)(*pf)(items[i]);}//main.cpp#include "list.h"void show_s(Item & item);int main(){List st;char ch;unsigned long po;unsigned long *p = &po;cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";while (cin >> ch && toupper(ch) != 'Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case 'A':case 'a':cout << "Enter a PO number to add: ";cin >> po;if (st.isfull())cout << "stack already full\n";elsest.add(po);break;case 'P':case 'p':if (st.isempty())cout << "stack already empty\n";else{st.cut(po);cout << "PO #" << po << "popped\n";}break;case 'V':case 'v':st.visit(show_s);}cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";}st.show();cout << "Bye\n";cin.get();cin.get();return 0;}void show_s(Item &item){item += 100;cout << item << endl;}。

C++ Primer Plus(第6版)中文版》编程练习答案第6-10章

C++ Primer Plus(第6版)中文版》编程练习答案第6-10章

第6章分支语句和逻辑运算符//ex6.1#include<iostream>#include<cctype>int main(){using namespace std;char ch;cin.get(ch);while (ch != '@'){if (!isdigit(ch)){if (isupper(ch))ch = tolower(ch);else if (islower(ch))ch = toupper(ch);cout << ch;}cin.get(ch);}return 0;}//ex6.2#include<iostream>const int Max = 10;int main(){using namespace std;double num[Max];int i = 0;cout << "Number 1: ";while (i < Max && cin >> num[i]){if (++i < Max)cout << "Number " << i+1 << ": ";}double total = 0.0;for (int j = 0; j < i; j++)total += num[j];double Average = total/i;cout << "Average = " << Average << endl;int q = 0;for (int j = 0; j < i; j++)if (num[j] > Average)q++;cout << q << " numbers > average.\n";return 0;}//ex6.3#include<iostream>int main(){using namespace std;char ch;cout << "Please enter one of the choice:\n"<< "c) carnivore p) pianist\n"<< "t) tree g) game\n";cin >> ch;while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g'){cout << "Please enter a c, p, t, or g: ";cin >> ch;}switch (ch){case'c' : cout << "A cat is a carnivore.\n";break;case'p' : cout << "Radu Lupu is a pianist.\n";break;case't' : cout << "A maple is a tree.\n";break;case'g' : cout << "Golf is a game.\n";break;default : cout << "The program shouldn't get here!\n";}return 0;}//ex6.4#include<iostream>const int strsize = 20;struct bop{char fullname[strsize];char title[strsize];char bopname[strsize];int preference;};int main(){using namespace std;bop member[5] = {{"Wimp Macho", "English Teacher", "DEMON", 0},{"Raki Rhodes", "Junior Programmer", "BOOM", 1},{"Celia Laiter", "Super Star", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WATEE", 1},{"Pat Hand", "Police", "LOOPY", 2}};char ch;cout << "Benevolent Order of Programmers Report\n"<< "a. display by name b. display by title\n"<< "c. display by bopname d. display by preference\n"<< "q. quit\n";cout << "Enter your choice: ";while (cin >> ch && ch != 'q'){switch (ch){case'a': for (int i = 0; i < 5; i++)cout << member[i].fullname << endl;break;case'b': for (int i = 0; i < 5; i++)cout << member[i].title << endl;break;case'c': for (int i = 0; i < 5; i++)cout << member[i].bopname << endl;break;case'd': for (int i = 0; i < 5; i++){if (member[i].preference == 0)cout << member[i].fullname << endl;else if (member[i].preference == 1)cout << member[i].title << endl;elsecout << member[i].bopname << endl;}break;}cout << "Next choice: ";}cout << "Bye!" << endl;return 0;}//ex6.5#include<iostream>const double LEV1 = 5000;const double LEV2 = 15000;const double LEV3 = 35000;const double RATE1 = 0.10;const double RATE2 = 0.15;const double RATE3 = 0.20;int main(){using namespace std;double income, tax;cout << "Enter your annual income in tvarps: ";cin >> income;if (income <= LEV1)tax = 0;else if (income <= LEV2)tax = (income - LEV1) * RATE1;else if (income <= LEV3)tax = RATE1 * (LEV2 - LEV1) + RATE2 * (income - LEV2);elsetax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2)+ RATE3 * (income - LEV3);cout << "You owe Neutronia " << tax << " tvarps in taxes.\n";return 0;}//ex6.6#include<iostream>#include<string>using namespace std;struct Patrons{string name;double money;};int main(){cout << "输入捐赠者的数目: ";int num;cin >> num;Patrons* ps = new Patrons[num];cout << "输入每一个捐赠者的姓名和款项:\n";for (int i=0; i<num; i++){cout << "输入第" << i+1 << "位姓名: ";cin >> ps[i].name;cout << "输入第" << i+1 << "位款项: ";cin >> ps[i].money;}cout << "Grand Patron\n";for (int i=0; i<num; i++){if (ps[i].money > 10000)cout << ps[i].name << endl;}cout << "\nPatron\n";for (int i=0; i<num; i++){if (ps[i].money <= 10000)cout << ps[i].name << endl;}return 0;}//ex6.7#include<iostream>#include<string>#include<cctype>int main(){using namespace std;string word;int vowel = 0;int consonant = 0;int other = 0;char ch;cout << "Enter words (q to quit):\n";cin >> word;while (word != "q"){ch = tolower(word[0]);if (isalpha(ch)){if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')vowel ++;elseconsonant ++;}elseother ++;cin >> word;}cout << vowel << " words beginning with vowel\n"<< consonant << " words beginning with consonants\n"<< other << " others\n";return 0;}//ex6.8#include<iostream>#include<fstream>#include<cstdlib>const int SIZE = 60;int main(){using namespace std;char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int count = 0;char ch;inFile >> ch;while (inFile.good()){count ++;inFile >> ch; // get next value}cout << count << " characters in " << filename << endl;inFile.close(); // finished with the filereturn 0;}//ex6.9#include<iostream>#include<string>#include<fstream>#include<cstdlib>const int SIZE = 60;using namespace std;struct Patrons{string name;double money;};int main(){char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int num;inFile >> num;inFile.get();Patrons* ps = new Patrons[num];for (int i = 0; i<num; i++){getline(inFile, ps[i].name);inFile >> ps[i].money;inFile.get();}cout << "\nGrand Patrons:\n";int count1 = 0;for (int i = 0; i < num; i++){if (ps[i].money > 10000){cout << ps[i].name <<endl;count1++;}}if (count1 == 0)cout << "none";cout << "\nPatrons:\n";int count2 = 0;for (int i = 0; i < num; i++){if (ps[i].money <= 10000){cout << ps[i].name <<endl;count2++;}}if (count2 == 0)cout << "none";delete [] ps;inFile.close();return 0;}第7章函数——C++的编程模块//ex7.1#include<iostream>double t_av(double x, double y);int main(){using namespace std;double x, y;double result;cout << "Please enter two numbers (0 to stop): ";while ((cin >> x >> y) && x != 0 && y != 0){result = t_av(x, y);cout << "调和平均数 = " << result << endl;cout << "Please enter two numbers (0 to stop): ";}return 0;}double t_av(double x, double y){return 2.0 * x * y / (x + y);}//ex7.2#include<iostream>const int MAX = 10;using namespace std;int fill_ar(double ar[], int limit);void show_ar(const double ar[], int n);double average(const double ar[], int n);int main(){double scores[MAX];int size = fill_ar(scores, MAX);show_ar(scores, size);if (size > 0)cout << "The average of scores is: "<< average(scores, size) << endl;return 0;}int fill_ar(double ar[], int limit){double temp;int i;for (i = 0; i < limit; i++){cout << "Enter score #" << i+1 << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; enter a number: ";break;}if (temp < 0)break;ar[i] = temp;}return i;}void show_ar(const double ar[], int n){for (int i = 0; i < n; i++)cout << "score #" << i+1 << ": " << ar[i] << endl; }double average(const double ar[], int n){double sum = 0.0;for (int i = 0; i < n; i++)sum += ar[i];return sum / n;}//ex7.3#include<iostream>struct box{char maker[40];float height;float width;float length;float volume;};void set_box(box *);void show_box(box);int main(){using namespace std;box carton = {"Bingo Boxer", 2, 3, 5};set_box(&carton);show_box(carton);return 0;}void set_box(box * pb){pb->volume = pb->height * pb->length * pb->width;}void show_box(box b){using namespace std;cout << "Box maker: " << b.maker<< "\nheight: " << b.height<< "\nlwidth: " << b.width<< "\nlength: " << b.length<< "\nvolume: " << b.volume << endl;}//ex7.4#include<iostream>long double probability(unsigned numbers, unsigned picks);int main(){using namespace std;double total, choices, mtotal;long double probability1, probability2;cout << "Enter total number of game card choices and\n""number of picks allowed for the field:\n";while ((cin >> total >> choices) && choices < total){cout << "Enter total number of game card choices and\n""number of picks allowed for the mega:\n";if (!(cin >> mtotal))break;probability1 = probability(total, choices);probability2 = probability(mtotal, 1);cout << "The chances of getting all "<< choices << " picks is one in "<< probability1 << ".\n";cout << "The chances of getting the megaspot is one in "<< probability2 << ".\n";cout << "You have one chance in ";cout << probability1 * probability2;cout << " of winning.\n";cout << "Next set of numbers (q to quit): ";}cout << "bye\n";return 0;}long double probability(unsigned numbers, unsigned picks){long double result = 1.0;long double n;unsigned p;for (n = numbers, p = picks; p > 0; n--, p--)result = result * n / p;return result;}//ex7.5#include<iostream>long long int recure(int);int main(){using namespace std;int number;cout << "Enter a integer (q to stop): ";while (cin >> number){long long int result = recure(number);cout << number << "! = " << result << endl;cout << "Next:";}cout << "Done!" << endl;return 0;}long long int recure(int n){long long int result;if (n > 0)result = n * recure(n-1);elseresult = 1;return result;}//ex7.6#include<iostream>const int Size = 10;int Fill_array(double ar[], int n);void Show_array(const double ar[], int n); void Reverse_array(double ar[], int n);int main(){using namespace std;double values[Size];int len = Fill_array(values, Size);cout << "Array values:\n";Show_array(values, len);cout << "Array reversed:\n";Reverse_array(values, len);Show_array(values, len);cout << "All but end values reversed:\n";Reverse_array(values+1, len-2);Show_array(values, len);return 0;}int Fill_array(double ar[], int n){using namespace std;double temp;int i;for (i=0; i<n; i++){cout << "Enter value #" << i+1 << ": ";cin >> temp;if (!cin)break;ar[i] = temp;}cout << endl;return i;}void Show_array(const double ar[], int n){using namespace std;for (int i=0; i<n; i++)cout << "Property #" << i+1 << ": "<< ar[i] << endl;cout << endl;}void Reverse_array(double ar[], int n){double temp;for (int i=0,j=n-1; i<j; i++,j--){temp = ar[i];ar[i] = ar[j];ar[j] = temp;}}//ex7.7#include<iostream>const int Max = 5;double * fill_array(double * begin, double * end);void show_array(const double * begin, const double * end); void revalue(double r, double * begin, double * end);int main(){using namespace std;double properties[Max];double * pbegin = properties;double * pend = fill_array(pbegin, pbegin + Max);show_array(pbegin, pend);if (pend-pbegin > 0){cout << "Enter revaluation factor: ";double factor;while (!(cin >> factor)){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; Please enter a number: ";}revalue(factor, pbegin, pend);show_array(pbegin, pend);}cout << "Done.\n";return 0;}double * fill_array(double * begin, double * end){using namespace std;double temp;int i = 1;while (begin < end){cout << "Enter value #" << i << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; input process terminated.\n";break;}else if (temp < 0)break;*begin = temp;begin++;i++;}return begin;}void show_array(const double * begin, const double * end){using namespace std;int i = 1;while (begin < end){cout << "Property #" << i << ": $";cout << *begin << endl;begin++;i++;}}void revalue(double r, double * begin, double * end){while (begin < end){*begin *= r;begin++;}}//ex7.8a#include<iostream>const int Seasons = 4;const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(double ar[], int n);void show(double ar[], int n);int main(){using namespace std;double expenses[Seasons];fill(expenses, Seasons);show(expenses, Seasons);return 0;}void fill(double ar[], int n){using namespace std;for (int i=0; i<n; i++){cout << "Enter " << Snames[i] << " expenses: ";cin >> ar[i];}}void show(double ar[], int n){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<n; i++){cout << Snames[i] << ": $" << ar[i] <<endl;total += ar[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构值)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; data fill();void show(data);int main(){using namespace std;data expenses = fill();show(expenses);return 0;}data fill(){using namespace std;data expenses;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> expenses.arr[i];}return expenses;}void show(data expenses){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << expenses.arr[i] <<endl;total += expenses.arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构指针)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(data * pd);void show(data * pd);int main(){using namespace std;data expenses;fill(&expenses);show(&expenses);return 0;}void fill(data * pd){using namespace std;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> pd->arr[i];}}void show(data * pd){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << pd->arr[i] <<endl;total += pd->arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.9#include<iostream>using namespace std;const int SLEN = 30;struct student {char fullname[SLEN];char hobby[SLEN];int ooplevel;};int getinfo(student pa[], int n);void display1(student st);void display2(const student * ps);void display3(const student pa[], int n);int main(){cout << "Enter class size: ";int class_size;cin >> class_size;while (cin.get() != '\n')continue;student * ptr_stu = new student[class_size];int entered = getinfo(ptr_stu, class_size);for (int i = 0; i < entered; i++)display1(ptr_stu[i]);display2(&ptr_stu[i]);}display3(ptr_stu, entered);delete [] ptr_stu;cout << "Done\n";return 0;}// getinfo() has two arguments: a pointer to the first element of // an array of student structures and an int representing the// number of elements of the array. The function solicits and// stores data about students. It terminates input upon filling// the array or upon encountering a blank line for the student// name. The function returns the actual number of array elements // filled.int getinfo(student pa[], int n){int num_array_elem = n;char tmp[SLEN];for (int i = 0; i < n; ++i){cout << "Enter name: ";cin.getline(tmp, SLEN);bool blank_line = true;for (unsigned j = 0; j < strlen(tmp); ++j){if (!isspace(tmp[j])){blank_line = false;break;}}if (blank_line){num_array_elem = i;break;}strcpy(pa[i].fullname, tmp);cout << "Enter hobby: ";cin.getline(pa[i].hobby, SLEN);cout << "Enter ooplevel: ";cin >> pa[i].ooplevel;cin.get();}cout << endl;return num_array_elem;}// display1() takes a student structure as an argument// and displays its contentsvoid display1(student st){cout << st.fullname << '\t'<< st.hobby << '\t'<< st.ooplevel << endl;}// display2() takes the address of student structure as an// argument and displays the structure’¡¥s contentsvoid display2(const student * ps){cout << ps->fullname << '\t'<< ps->hobby << '\t'<< ps->ooplevel << endl;}// display3() takes the address of the first element of an array// of student structures and the number of array elements as// arguments and displays the contents of the structuresvoid display3(const student pa[], int n){for (int i = 0; i < n; ++i)cout << pa[i].fullname << '\t' << pa[i].hobby << '\t' <<pa[i].ooplevel << endl;}//ex7.10#include<iostream>double calculate(double x, double y, double (*pf)(double, double)); double add(double x, double y);double sub(double x, double y);double mean(double x, double y);int main(){using namespace std;double a, b;double (*pf[3])(double, double) = {add, sub, mean};char * op[3] = {"add", "sub", "mean"};cout << "Enter pairs of numbers (q to quit): ";while (cin >> a >> b){for (int i=0; i<3; i++){cout << op[i] << ": " << a << " and " << b << " = "<< calculate(a, b, pf[i]) << endl;}}}double calculate(double x, double y, double (*pf)(double, double)) {return (*pf)(x, y);}double add(double x, double y){return x + y;}double sub(double x, double y){return x - y;}double mean(double x, double y){return (x + y) / 2.0;}第8章函数探幽//ex8.1#include<iostream>void show(const char * ps, int n = 0);int main(){using namespace std;char * pstr = "Hello\n";show(pstr);int num;cout << "Enter a number: ";cin >> num;show(pstr, num);cout << "Done\n";return 0;}void show(const char * ps, int n){using namespace std;int lim = n;if (n == 0)lim = 1;for (int i=0; i<lim; i++)cout << ps;}//ex8.2#include<iostream>#include<string>using namespace std;struct CandyBar{string name;double weight;int hot;};void set(CandyBar & cb, char * ps, double w, int h); void show(const CandyBar & cb);int main(){using namespace std;CandyBar candy;char * p = "Millennium Munch";double x = 2.85;int y = 350;set(candy, p, x, y);show(candy);return 0;}void set(CandyBar & cb, char * ps, double w, int h){ = ps;cb.weight = w;cb.hot = h;}void show(const CandyBar & cb){cout << "Name: " << << endl<< "Weight: " << cb.weight << endl<< "Hot: " << cb.hot << endl;}//ex8.3#include<iostream>#include<string>#include<cctype>using namespace std;void str_to_upper(string & str);int main(){string str1;cout << "Enter a string (q to quit): ";while (getline(cin, str1) && str1!="q" && str1!="Q") {str_to_upper(str1);cout << str1 << endl;cout << "Next string (q to quit): ";}cout << "Bye.";return 0;}void str_to_upper(string & str){int limit = str.size();for (int i=0; i<limit; i++){if (isalpha(str[i]))str[i] = toupper(str[i]);}}// ex8.4#include<iostream>#include<cstring>// for strlen(), strcpy()using namespace std;struct stringy {char * str; // points to a stringint ct; // length of string (not counting '\0')};void show(const char *str, int cnt = 1);void show(const stringy & bny, int cnt = 1);void set(stringy & bny, const char * str);int main(void){stringy beany;char testing[] = "Reality isn't what it used to be.";set(beany, testing); // first argument is a reference,// allocates space to hold copy of testing,// sets str member of beany to point to the// new block, copies testing to new block,// and sets ct member of beany show(beany); // prints member string onceshow(beany, 2); // prints member string twicetesting[0] = 'D';testing[1] = 'u';show(testing); // prints testing string onceshow(testing, 3); // prints testing string thriceshow("Done!");return 0;}void show(const char *str, int cnt){while(cnt-- > 0)cout << str << endl;}}void show(const stringy & bny, int cnt){while(cnt-- > 0){cout << bny.str << endl;}}void set(stringy & bny, const char * str){bny.ct = strlen(str);bny.str = new char[bny.ct+1];strcpy(bny.str, str);}//ex8.5#include<iostream>const int Limit = 5;template <typename T>T max5(T ar[]);int main(){using namespace std;int ari[Limit] = {1, 2, 3, 5, 4};double ard[Limit] = {1.1, 2.2, 3.3, 5.5, 4.4};int maxi = max5(ari);double maxd = max5(ard);cout << "maxi = " << maxi << endl;cout << "maxd = " << maxd << endl;return 0;}template <typename T>T max5(T ar[]){T max = ar[0];for (int i=1; i<Limit; i++)if (max < ar[i])max = ar[i];}return max;}//ex8.6#include<iostream>template <typename T>T maxn(T ar[], int n);template <> const char* maxn(const char* ar[], int n);int main(){using namespace std;int ari[6] = {1, 2, 3, 4, 6, 5};double ard[4] = {1.1, 2.2, 4.4, 3.3};const char * ars[5] = {"a","bb","ccc","ddddd","eeee"};cout << "The max integer of array is: " << maxn(ari, 6) << endl;cout << "The max double of array is: " << maxn(ard, 4) << endl;cout << "The max string of array is: " << maxn(ars, 5)<<endl; }template <typename T>T maxn(T ar[], int n){T maxar = ar[0];for (int i=1; i<n; i++){if (maxar < ar[i])maxar = ar[i];}return maxar;}template <> const char* maxn(const char* ar[],int n) {const char * maxs = ar[0];for (int i=1; i<n; i++){if (strlen(maxs) < strlen(ar[i]))maxs = ar[i];}return maxs;}//ex8.7#include<iostream>template <typename T>T SumArrray(T arr[], int n);template <typename T>T SumArrray(T * arr[], int n);struct debts{char name[50];double amount;};int main(){using namespace std;int things[6] = {13, 31, 103, 301, 310, 130};struct debts mr_E[3] ={{"Ima Wolfe", 2400.0},{"Ura Foxe", 1300.0},{"Iby Stout", 1800.0}};double * pd[3];for (int i=0; i<3; i++)pd[i] = &mr_E[i].amount;cout << "Sum: Mr.E's counts of things: "<< SumArrray(things, 6) << endl;cout << "Sum: Mr.E's debts: "<< SumArrray(pd, 3) << endl;return 0;。

C++课后习题答案第十章

C++课后习题答案第十章
(b) outfile.write(( float* ) &data , data );
(c)outfile.write(( char* ) &data , sizeof( float ));
(d)outfile.write(( char* ) &data , data );
10.2
1.#include <iostream.h>
cout.setf(ios::right,ios::left);
cout <<x<< endl;
cout.setf( ios::showpos );
cout <<x<< endl;
cout <<-x<< endl;
cout.setf( ios :: scientific );
cout <<x<< endl;
}
答案:
123.456
123.456
123.456
+123.456
-123.456
+1.234560e+002
2.#include <iostream.h>
void main()
{ double x=123.45678;
cout.width(10);
cout<<("#");
cout <<x<< endl;
do
{
infile.read((char *)&gzrec,sizeof(txrec));
}while (strcmp(gzrec.no,num)!=0 && infile.tellp()!=posend);

面向对象的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_primer_plus(第五版)课后编程练习答案(完整)

C_primer_plus(第五版)课后编程练习答案(完整)
第一章 概览 编程练习
1.您刚刚被 MacroMuscle 有限公司(Software for Hard Bodies)聘用。该公司要进入欧洲市场,需 要一个将英寸转换为厘米(1 英寸=2.54 cm)的程序。他们希望建立的该程序可提示用户输入英寸值。您的 工作是定义程序目标并设计该程序(编程过程的第 1 步和第 2 步) 。
int toes_square; toes_add=toes+toes; toes_square=toes*toes; printf("toes=%d\ntoes_add=%d\ntoes_square=%d\n",toes,toes_add,toes_square); return(0); }
6.编写一个能够产生下列输出的程序: Smile ! Smile ! Smile Smile ! Smile ! Smile ! 在程序中定义一个能显示字符串 smile 卜一次的函数,并在需要时使用该函数。
5.编写一个程序,创建一个名为 toes 的整数变量。让程序把 toes 设置为 10。再让程序计算两个 toes 的和以及 toes 的平方。程序应该输出所有的 3 个值,并分别标识它们。
#include<stdio.h> int main(void) { int toes=10; int toes_add;
4.编写一个能够产生下面输出的程序: For he's a jolly good fellow! For he's a jolly good fellow! For he's a jolly good fellow!
Which nobody can deny! 程序中除了 main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次: 另一个用于把最后一行输出一次。

C Primer Plus第十章 编程练习答案

C Primer Plus第十章 编程练习答案

1.#include<stdio.h>#define MONTHS 12#define YEARS 5int main(void){constfloat rain[YEARS][MONTHS]={{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},{9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4},{7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 6.2},{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2} };constfloat (*p)[MONTHS];int year, month;float subtot, total;p=rain;printf("YEAR RAINFALL (inches)\n");for (year=0, total=0; year<YEARS; year++){for (month=0, subtot=0; month<MONTHS; month++){subtot +=p[year][month];}printf("%5d %15.1f\n", 2010+year, subtot);total +=subtot;}printf("The yearly average is %.1f inches.\n\n", total/YEARS);printf("MONTHLY AVERAGE:\n\n");printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");for (month=0; month<MONTHS; month++){for (year=0, subtot=0; year<YEARS; year++){subtot +=p[year][month];}printf("%4.1f ", subtot/YEARS);}printf("\n");getchar();return 0;}2.#include<stdio.h>#define SIZE 5void fun1( constdouble src[], double dst[], int n);void fun2(constdouble *src, double *dst, int n);void fun3(constdouble *src, double *dst, constdouble *end); int main(void){constdouble source[SIZE]={1.1, 2.2, 3.3, 4.4, 5.5};double target1[SIZE];double target2[SIZE];double target3[SIZE];int i;fun1(source, target1, SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target1[i]);}putchar('\n');fun2(source, target2, SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target2[i]);}putchar('\n');fun3(source, target3, source+SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target2[i]);}putchar('\n');getchar();return 0;}void fun1(constdouble src[], double dst[], int n){int i;for (i=0; i<n; i++){dst[i]=src[i];}}void fun2(constdouble *src, double *dst, int n){int i;for(i=0; i<n; i++){*(dst+i)= *(src +i );}}void fun3(constdouble *src, double *dst, constdouble *end) {while (src<end){*dst=*src;src++;dst++;}}3.#include<stdio.h>#define SIZE 10int findMax(int *arr, int n);int main(void){int i=0;int max;int arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%d", &arr[i]);i++;}max=findMax(arr, SIZE);printf("The max value of arr is %d\n", max);getchar();getchar();return 0;}int findMax(int *arr, int n){int i, max=0;for (i=0; i<n; i++){if (arr[i]>max){max=arr[i];}}return max;}4.#include<stdio.h>#define SIZE 10int findMaxIndex(double *arr, int n);int main(void){int i=0;int maxIndex;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}maxIndex=findMaxIndex(arr, SIZE);printf("The index of max value of arr is %d\n", maxIndex);getchar();getchar();return 0;}int findMaxIndex(double *arr, int n){int i, index;double max=0;for (i=0; i<n; i++){if (arr[i]>max){max=arr[i];index=i;}}return index;}5.#include<stdio.h>#define SIZE 10double diffMaxMin(double *arr, int n);int main(void){int i=0;double diffValue;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}diffValue=diffMaxMin(arr, SIZE);printf("The diff value of max and min in arr is %lf\n", diffValue);getchar();getchar();return 0;}double diffMaxMin(double *arr, int n) {double max=0, min=10000;int i;for(i=0; i<n; i++){if (arr[i]>max){max=arr[i];}if (arr[i]<min){min=arr[i];}}return (max-min);}6.#include<stdio.h>#define SIZE 10void sort(double *arr, int n);int main(void){int i=0;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}sort(arr, SIZE);for (i=0; i<SIZE; i++){printf("%4.1lf ", arr[i]);}putchar('\n');getchar();getchar();return 0;}void sort(double *arr, int n){double temp;int i;for(i=0; i<n/2; i++){temp=arr[i];arr[i]=arr[n-1-i];arr[n-1-i]=temp;}}7.#include<stdio.h>#define Rows 3#define Cols 5void copy(constdouble (*src)[Cols], double (*dst)[Cols], int n); int main(void){int i, j;constdouble source[Rows][Cols]={{1, 3, 4, 5, 6},{2, 6, 4, 6, 7},{3, 4, 6, 7, 10}};double target[Rows][Cols];copy(source, target, Rows);for (i=0; i<Rows; i++){for (j=0; j<Cols; j++){printf("%4.1lf ", target[i][j]);}}putchar('\n');getchar();getchar();return 0;}void copy(constdouble (*src)[Cols], double (*dst)[Cols], int n){int r, c;for(r=0; r<n; r++){for (c=0; c<Cols; c++){dst[r][c]=src[r][c]; //或者用指针表示法*(*(dst+r)+c)=*(*(src+r)+c);}}}8.#include<stdio.h>#define SIZE 7void copy(double *src, double *dst, int n);int main(void){int i=0;double arr[SIZE];double target[3];printf("Please input 7 numbers:\n");while (i<7){scanf("%lf", &arr[i]);i++;}copy(arr+2, target, 3);for (i=0; i<3; i++){printf("%4.1lf ", target[i]);}putchar('\n');getchar();getchar();return 0;}void copy(double *src, double *dst, int n) {int i;for (i=0; i<n; i++){*(dst+i)=*(src+i);}}10#include<stdio.h>#define SIZE 5void add(int *src1, int *src2, int* dst, int n); int main(void){int i;int arr1[SIZE], arr2[SIZE], target[SIZE];printf("Please input the first array: \n");for (i=0;i<SIZE; i++){scanf("%d", &arr1[i]);}printf("Please input the second array: \n");for (i=0;i<SIZE; i++){scanf("%d", &arr2[i]);}add(arr1, arr2, target, SIZE);printf("the final array: \n");for (i=0;i<SIZE; i++){printf("%d ", target[i] );}putchar('\n');getchar();getchar();return 0;}void add(int *src1, int *src2, int* dst, int n){int i;for (i=0; i<n; i++){*(dst+i)=*(src1+i)+*(src2+i);}}11.#include<stdio.h>#define ROWS 3#define COLS 5void display(int (*src)[COLS], int n);void mul(int (*src)[COLS], int (*dst)[COLS], int n); int main(void){int target[ROWS][COLS];int arr[ROWS][COLS]={{1, 2, 3, 4, 5},{4, 3, 4, 3, 1},{0, 9, 8,7, 6}};display(arr, ROWS);mul(arr, target, ROWS);display(target, ROWS);putchar('\n');getchar();getchar();return 0;}void display(int (*src)[COLS], int n){int i, j;for (i=0; i<ROWS; i++){for (j=0; j<COLS; j++){printf("%3d ", *(*(src+i)+j));}}}void mul(int (*src)[COLS], int (*dst)[COLS], int n){int i, j;for (i=0; i<ROWS; i++){for (j=0; j<COLS; j++){*(*(dst+i)+j)=*(*(src+i)+j) *2;}}putchar('\n');}12.#include<stdio.h>#define MONTHS 12#define YEARS 5void yearRain(constfloat (*src)[MONTHS], int n);void monthRain(constfloat (*src)[MONTHS], int n);int main(void){constfloat rain[YEARS][MONTHS]={{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},{9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4},{7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 6.2},{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2} };yearRain(rain, MONTHS);monthRain(rain, MONTHS);printf("\n");getchar();return 0;}void yearRain(constfloat (*src)[MONTHS], int n){int year, month;float subtot, total;printf("YEAR RAINFALL (inches)\n");for (year=0, total=0; year<YEARS; year++){for (month=0, subtot=0; month<MONTHS; month++){subtot +=src[year][month];}printf("%5d %15.1f\n", 2010+year, subtot);total +=subtot;}printf("The yearly average is %.1f inches.\n\n", total/YEARS);}void monthRain(constfloat (*src)[MONTHS], int n){int year, month;float subtot;printf("MONTHLY AVERAGE:\n\n");printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");for (month=0; month<MONTHS; month++){for (year=0, subtot=0; year<YEARS; year++){subtot +=src[year][month];}printf("%4.1f ", subtot/YEARS);}printf("\n");}13.#include<stdio.h>#define ROWS 3#define COLS 5void write(double(*src)[COLS], int n);double rowAverage(double(*src)[COLS], int n);double average(double(*src)[COLS], int n);double max(double(*src)[COLS], int n);void display(double(*src)[COLS], double *rowAve, double Ave, double maxValue, int n);int main(void){double arr[ROWS][COLS];double Rave[ROWS];double rowAve, Ave, Max;int i, j;write(arr, ROWS);for (i=0; i<ROWS; i++){rowAve=rowAverage(arr, i);Rave[i]=rowAve;}Ave=average(arr, ROWS);Max=max(arr, ROWS);display(arr, Rave, Ave, Max, ROWS);printf("\n");getchar();getchar();return 0;}void write(double(*src)[COLS], int n){int i, j;for (i=0;i<ROWS; i++){printf("Please input %d rows numbers: \n", i);for (j=0; j<COLS; j++){scanf("%lf", &src[i][j]);}}}double rowAverage(double(*src)[COLS], int n) {int j;double Raverage, sum;sum=0;for (j=0; j<COLS; j++){sum +=src[n][j];}Raverage=sum/COLS;return Raverage;}double average(double(*src)[COLS], int n) {int i, j;double sum, average;sum=0;for (i=0; i<n; i++){for(j=0; j<COLS; j++){sum +=src[i][j];}}average=sum/(n*COLS);return average;}double max(double(*src)[COLS], int n){double max=0;int i, j;for (i=0; i<n; i++){for(j=0; j<COLS; j++){if (src[i][j]>max){max=src[i][j];}}}return max;}void display(double(*src)[COLS], double *rowAve, double Ave, double maxValue, int n){int i, j;printf("The array you have entered: \n");for (i=0; i<n; i++){for (j=0; j<COLS; j++){printf("%4.1lf", src[i][j]);}putchar('\n');}putchar('\n');printf("The every row average of the array you have entered: \n");for (i=0; i<n; i++){printf("%4.1f\n", rowAve[i]);}printf("The average of the array you have entered: \n");printf("%4.1f\n", Ave);printf("The max value of the array you have entered: \n");printf("%4.1f\n", maxValue);}。

C++PrimerPlus第五版第十章习题参考答案

C++PrimerPlus第五版第十章习题参考答案

C++PrimerPlus第五版第十章习题参考答案Chapter 10PE 10-1// pe10-1.cpp#include#include// class declarationclass BankAccount{private:char name[40];char acctnum[25];double balance;public:BankAccount(char * client = "no one", char * num = "0",double bal = 0.0); void show(void) const;void deposit(double cash); void withdraw(double cash); };// method definitionsBankAccount::BankAccount(char * client, char * num, double bal) {std::strncpy(name, client, 39);name[39] = '\0';std::strncpy(acctnum, num, 24);acctnum[24] = '\0';balance = bal;}void BankAccount::show(void) const{using std::cout;using std:: endl;cout << "Client: " << name << endl;cout << "Account Number: " << acctnum << endl;cout << "Balance: " << balance << endl;}void BankAccount::deposit(double cash){if (cash >= 0)balance += cash;elsestd::cout << "Illegal transaction attempted";}void BankAccount::withdraw(double cash){if (cash < 0)std::cout << "Illegal transaction attempted";else if (cash <= balance)balance -=cash;elsestd::cout << "Request denied due to insufficient funds.\n"; } // sample useint main(){BankAccount bird;BankAccount frog("Kermit", "croak322", 123.00);bird.show();frog.show();bird = BankAccount("Chipper", "peep8282", 214.00); bird.show();frog.deposit(20);frog.show();frog.withdraw(4000);frog.show();frog.withdraw(50);frog.show();}PE10-4// pe10-4.h#ifndef SALES__#define SALES__namespace SALES{const int QUARTERS = 4;class Sales{private:double sales[QUARTERS];double average;double max;double min;public:// default constructorSales();// copies the lesser of 4 or n items from the array ar// to the sales member and computes and stores the// average, maximum, and minimum values of the entered items;// remaining elements of sales, if any, set to 0Sales(const double ar[], int n);// gathers sales for 4 quarters interactively, stores them// in the sales member of object and computes and stores the// average, maximum, and minumum valuesvoid setSales();// display all information in objectvoid showSales();};}#endif// pe10-4a.cpp#include#include "pe10-4.h"int main(){using SALES::Sales;double vals[3] = {2000, 3000, 5000};Sales forFiji(vals, 3);forFiji.showSales();Sales red;red.showSales();red.setSales();red.showSales();return 0;}// pe10-4b.cpp#include#include "pe10-4.h"namespace SALES{using std::cin;using std::cout;using std::endl;Sales::Sales(const double ar[], int n){if (n < 0)n = 0;int limit = n < QUARTERS ? n : QUARTERS; double total = 0;min = 0;max = 0;average = 0;if (limit > 0)min = max = ar[0];int i;for (i = 0; i < limit; i++){sales[i] = ar[i];total += ar[i];if (ar[i] > max)max = ar[i];else if (ar[i] < min)min = ar[i];}for (i = limit; i < QUARTERS; i++)sales[i] = 0;if (limit > 0)average = total / limit;}Sales::Sales(){min = 0;max = 0;average = 0;for (int i = 0; i < QUARTERS; i++)sales[i] =0;}void Sales::setSales(){double sa[QUARTERS];int i;for (i = 0; i < QUARTERS; i++){cout << "Enter sales for quarter " << i + 1 << ": "; cin >> sa[i];}// create temporary object, copy to invoking object *this = Sales(sa, QUARTERS);}void Sales::showSales(){cout << "Sales:\n";for (int i = 0; i < QUARTERS; i++)cout << "Quarter " << i + 1 << ": $"<< sales[i] << endl;cout << "Average: $" << average << endl;cout << "Minimum: $" << min << endl;cout << "Maximum: $" << max << endl;}}PE 10-5// pe10stack.h -- class definition for the stack ADT// for use with pe10-5.cpp#ifndef _STACK_H_#define _STACK_H_struct customer {char fullname[35];double payment;};typedef customer Item;class Stack{private:enum {MAX = 10}; // constant specific to classItem items[MAX]; // holds stack itemsint top; // index for top stack itempublic:Stack();bool isempty() const;bool isfull() const;// push() returns false if stack already is full, true otherwise bool push(const Item & item); // add item to stack// pop() returns false if stack already is empty, true otherwise bool pop(Item & item); // pop top into item};#endif// pe10stack.cpp -- Stack member functions// for use with pe10-5.cpp// exactly the same as stack.cpp in the text#include "pe10stack.h"Stack::Stack() // create an empty stack{top = 0;}bool Stack::isempty() const{return top == 0;}bool Stack::isfull() const{return top == MAX;bool Stack::push(const Item & item) {if (top < MAX){items[top++] = item;return true;}elsereturn false;}bool Stack::pop(Item & item){if (top > 0){item = items[--top];return true;}elsereturn false;}// pe10-5.cpp#include#include#include "pe10stack.h" // modified to define customer structure // link with pe10stack.cppvoid get_customer(customer & cu);int main(void){using namespace std;Stack st; // create a stack of customer structurescustomer temp;double payments = 0;char c;cout << "Please enter A to add a customer,\n"<< "P to process a customer, and Q to quit.\n";while (cin >> c && (c = toupper(c)) != 'Q'){while (cin.get() != '\n')continue;if (c != 'A' && c != 'P'){cout << "Please respond with A, P, or Q: ";continue;}switch (c){case 'A' : if (st.isfull())cout << "stack already full\n";else{get_customer(temp);st.push(temp);}break;case 'P' : if (st.isempty())cout << "stack already empty\n";else {st.pop(temp);payments += temp.payment;cout << temp.fullname << " processed. ";cout << "Payments now total $"<< payments << "\n";}break;default : cout << "Whoops! Programming error!\n"; }cout << "Please enter A to add a customer,\n"<< "P to process a customer, and Q to quit.\n";}cout << "Done!\n";return 0;}void get_customer(customer & cu){using namespace std;cout << "Enter customer name: ";cin.getline(cu.fullname,35);cout << "Enter customer payment: ";cin >> cu.payment;while (cin.get() != '\n')continue;}PE 10-8// pe10-8arr.h -- header file for a simple list class#ifndef SIMPLEST_#define SIMPLEST_// program-specific declarationsconst int TSIZE = 45; // size of array to hold title struct film {char title[TSIZE];int rating;};// general type definitionstypedef struct film Item;const int MAXLIST = 10;class simplist{private:Item items[MAXLIST];int count;public:simplist(void);bool isempty(void);bool isfull(void);int itemcount();bool additem(Item item);void transverse( void (*pfun)(Item item));};#endif// pe10-8arr.cpp -- functions supporting simple listoperations #include "pe10-8arr.h"simplist::simplist(void){count = 0;}bool simplist::isempty(void){return count == 0;}bool simplist::isfull(void){return count == MAXLIST;}int simplist::itemcount(){return count;}bool simplist::additem(Item item){if (count == MAXLIST)return false;elseitems[count++] = item;return true;}void simplist::transverse( void (*pfun)(Item item)) {for (int i = 0; i < count; i++)(*pfun)(items[i]);}// pe10-8.cpp -- using a class definition#include#include // prototype for exit()#include "pe10-8arr.h" // simple list class declaration// array version void showmovies(Item item); // to be used by transverse() int main(void){using namespace std;simplist movies; // creates an empty listItem temp;if (movies.isfull()) // invokes isfull() member function{cout << "No more room in list! Bye!\n";exit(1);}cout << "Enter first movie title:\n";while (cin.getline(temp.title,TSIZE) && temp.title[0] != '\0') { cout << "Enter your rating <0-10>: ";cin >> temp.rating;while(cin.get() != '\n')continue;if (movies.additem(temp) == false){cout << "List already is full!\n";break;}if (movies.isfull()){cout << "You have filled the list.\n";break;}cout << "Enter next movie title (empty line to stop):\n"; }if (movies.isempty())cout << "No data entered. ";else{cout << "Here is the movie list:\n";movies.transverse(showmovies);}cout << "Bye!\n";return 0;}void showmovies(Item item){std::cout << "Movie: " << item.title << " Rating: "<< item.rating << std::endl;}。

C++Primer课后习题解答(第1~18章完整答案)完整版

C++Primer课后习题解答(第1~18章完整答案)完整版

目录第一章快速入门 (2)第二章变量和基本类型 (7)第三章标准库类型 (13)第四章数组和指针 (21)第五章表达式 (31)第六章语句 (37)第七章函数 (37)第八章标准IO库 (37)第九章顺序容器 (43)第十章关联容器 (60)第十一章泛型算法 (75)第十二章类和数据抽象 (86)第十三章复制控制 (94)第十四章重载操作符与转换 (102)第十五章面向对象编程 (116)第十六章部分选做习题 (133)第十七章用于大型程序的工具 (138)第十八章特殊工具与技术 (138)第一章快速入门习题 1.1查看所用的编译器文档,了解它所用的文件命名规范。

编译并运行本节的main程序。

【解答】一般而言,C++编译器要求待编译的程序保存在文件中。

C++程序中一般涉及两类文件:头文件和源文件。

大多数系统中,文件的名字由文件名和文件后缀(又称扩展名)组成。

文件后缀通常表明文件的类型,如头文件的后缀可以是.h 或.hpp 等;源文件的后缀可以是.cc 或.cpp 等,具体的后缀与使用的编译器有关。

通常可以通过编译器所提供的联机帮助文档了解其文件命名规范。

习题1.2修改程序使其返回-1。

返回值-1 通常作为程序运行失败的指示器。

然而,系统不同,如何(甚至是否)报告main 函数运行失败也不同。

重新编译并再次运行程序,看看你的系统如何处理main 函数的运行失败指示器。

【解答】笔者所使用的Windows 操作系统并不报告main 函数的运行失败,因此,程序返回-1 或返回0 在运行效果上没有什么区别。

但是,如果在DOS 命令提示符方式下运行程序,然后再键入echo %ERRORLEVEL%命令,则系统会显示返回值-1。

习题1.3编一个程序,在标准输出上打印“Hello, World”。

【解答】#include<iostream>int main(){std::cout << "Hello, World" << std::endl;return 0;}习题1.4我们的程序利用内置的加法操作符“+”来产生两个数的和。

C Primer Plus第十章 编程练习答案

C Primer Plus第十章 编程练习答案

1.#include<stdio.h>#define MONTHS 12#define YEARS 5int main(void){constfloat rain[YEARS][MONTHS]={{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},{9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4},{7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 6.2},{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2} };constfloat (*p)[MONTHS];int year, month;float subtot, total;p=rain;printf("YEAR RAINFALL (inches)\n");for (year=0, total=0; year<YEARS; year++){for (month=0, subtot=0; month<MONTHS; month++){subtot +=p[year][month];}printf("%5d %15.1f\n", 2010+year, subtot);total +=subtot;}printf("The yearly average is %.1f inches.\n\n", total/YEARS);printf("MONTHLY AVERAGE:\n\n");printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");for (month=0; month<MONTHS; month++){for (year=0, subtot=0; year<YEARS; year++){subtot +=p[year][month];}printf("%4.1f ", subtot/YEARS);}printf("\n");getchar();return 0;}2.#include<stdio.h>#define SIZE 5void fun1( constdouble src[], double dst[], int n);void fun2(constdouble *src, double *dst, int n);void fun3(constdouble *src, double *dst, constdouble *end); int main(void){constdouble source[SIZE]={1.1, 2.2, 3.3, 4.4, 5.5};double target1[SIZE];double target2[SIZE];double target3[SIZE];int i;fun1(source, target1, SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target1[i]);}putchar('\n');fun2(source, target2, SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target2[i]);}putchar('\n');fun3(source, target3, source+SIZE);for (i=0; i<SIZE; i++){printf("%.1lf ", target2[i]);}putchar('\n');getchar();return 0;}void fun1(constdouble src[], double dst[], int n){int i;for (i=0; i<n; i++){dst[i]=src[i];}}void fun2(constdouble *src, double *dst, int n){int i;for(i=0; i<n; i++){*(dst+i)= *(src +i );}}void fun3(constdouble *src, double *dst, constdouble *end) {while (src<end){*dst=*src;src++;dst++;}}3.#include<stdio.h>#define SIZE 10int findMax(int *arr, int n);int main(void){int i=0;int max;int arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%d", &arr[i]);i++;}max=findMax(arr, SIZE);printf("The max value of arr is %d\n", max);getchar();getchar();return 0;}int findMax(int *arr, int n){int i, max=0;for (i=0; i<n; i++){if (arr[i]>max){max=arr[i];}}return max;}4.#include<stdio.h>#define SIZE 10int findMaxIndex(double *arr, int n);int main(void){int i=0;int maxIndex;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}maxIndex=findMaxIndex(arr, SIZE);printf("The index of max value of arr is %d\n", maxIndex);getchar();getchar();return 0;}int findMaxIndex(double *arr, int n){int i, index;double max=0;for (i=0; i<n; i++){if (arr[i]>max){max=arr[i];index=i;}}return index;}5.#include<stdio.h>#define SIZE 10double diffMaxMin(double *arr, int n);int main(void){int i=0;double diffValue;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}diffValue=diffMaxMin(arr, SIZE);printf("The diff value of max and min in arr is %lf\n", diffValue);getchar();getchar();return 0;}double diffMaxMin(double *arr, int n) {double max=0, min=10000;int i;for(i=0; i<n; i++){if (arr[i]>max){max=arr[i];}if (arr[i]<min){min=arr[i];}}return (max-min);}6.#include<stdio.h>#define SIZE 10void sort(double *arr, int n);int main(void){int i=0;double arr[10];printf("Please input 10 numbers:\n");while (i<10){scanf("%lf", &arr[i]);i++;}sort(arr, SIZE);for (i=0; i<SIZE; i++){printf("%4.1lf ", arr[i]);}putchar('\n');getchar();getchar();return 0;}void sort(double *arr, int n){double temp;int i;for(i=0; i<n/2; i++){temp=arr[i];arr[i]=arr[n-1-i];arr[n-1-i]=temp;}}7.#include<stdio.h>#define Rows 3#define Cols 5void copy(constdouble (*src)[Cols], double (*dst)[Cols], int n); int main(void){int i, j;constdouble source[Rows][Cols]={{1, 3, 4, 5, 6},{2, 6, 4, 6, 7},{3, 4, 6, 7, 10}};double target[Rows][Cols];copy(source, target, Rows);for (i=0; i<Rows; i++){for (j=0; j<Cols; j++){printf("%4.1lf ", target[i][j]);}}putchar('\n');getchar();getchar();return 0;}void copy(constdouble (*src)[Cols], double (*dst)[Cols], int n){int r, c;for(r=0; r<n; r++){for (c=0; c<Cols; c++){dst[r][c]=src[r][c]; //或者用指针表示法*(*(dst+r)+c)=*(*(src+r)+c);}}}8.#include<stdio.h>#define SIZE 7void copy(double *src, double *dst, int n);int main(void){int i=0;double arr[SIZE];double target[3];printf("Please input 7 numbers:\n");while (i<7){scanf("%lf", &arr[i]);i++;}copy(arr+2, target, 3);for (i=0; i<3; i++){printf("%4.1lf ", target[i]);}putchar('\n');getchar();getchar();return 0;}void copy(double *src, double *dst, int n) {int i;for (i=0; i<n; i++){*(dst+i)=*(src+i);}}10#include<stdio.h>#define SIZE 5void add(int *src1, int *src2, int* dst, int n); int main(void){int i;int arr1[SIZE], arr2[SIZE], target[SIZE];printf("Please input the first array: \n");for (i=0;i<SIZE; i++){scanf("%d", &arr1[i]);}printf("Please input the second array: \n");for (i=0;i<SIZE; i++){scanf("%d", &arr2[i]);}add(arr1, arr2, target, SIZE);printf("the final array: \n");for (i=0;i<SIZE; i++){printf("%d ", target[i] );}putchar('\n');getchar();getchar();return 0;}void add(int *src1, int *src2, int* dst, int n){int i;for (i=0; i<n; i++){*(dst+i)=*(src1+i)+*(src2+i);}}11.#include<stdio.h>#define ROWS 3#define COLS 5void display(int (*src)[COLS], int n);void mul(int (*src)[COLS], int (*dst)[COLS], int n); int main(void){int target[ROWS][COLS];int arr[ROWS][COLS]={{1, 2, 3, 4, 5},{4, 3, 4, 3, 1},{0, 9, 8,7, 6}};display(arr, ROWS);mul(arr, target, ROWS);display(target, ROWS);putchar('\n');getchar();getchar();return 0;}void display(int (*src)[COLS], int n){int i, j;for (i=0; i<ROWS; i++){for (j=0; j<COLS; j++){printf("%3d ", *(*(src+i)+j));}}}void mul(int (*src)[COLS], int (*dst)[COLS], int n){int i, j;for (i=0; i<ROWS; i++){for (j=0; j<COLS; j++){*(*(dst+i)+j)=*(*(src+i)+j) *2;}}putchar('\n');}12.#include<stdio.h>#define MONTHS 12#define YEARS 5void yearRain(constfloat (*src)[MONTHS], int n);void monthRain(constfloat (*src)[MONTHS], int n);int main(void){constfloat rain[YEARS][MONTHS]={{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},{9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4},{7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 6.2},{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2} };yearRain(rain, MONTHS);monthRain(rain, MONTHS);printf("\n");getchar();return 0;}void yearRain(constfloat (*src)[MONTHS], int n){int year, month;float subtot, total;printf("YEAR RAINFALL (inches)\n");for (year=0, total=0; year<YEARS; year++){for (month=0, subtot=0; month<MONTHS; month++){subtot +=src[year][month];}printf("%5d %15.1f\n", 2010+year, subtot);total +=subtot;}printf("The yearly average is %.1f inches.\n\n", total/YEARS);}void monthRain(constfloat (*src)[MONTHS], int n){int year, month;float subtot;printf("MONTHLY AVERAGE:\n\n");printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");for (month=0; month<MONTHS; month++){for (year=0, subtot=0; year<YEARS; year++){subtot +=src[year][month];}printf("%4.1f ", subtot/YEARS);}printf("\n");}13.#include<stdio.h>#define ROWS 3#define COLS 5void write(double(*src)[COLS], int n);double rowAverage(double(*src)[COLS], int n);double average(double(*src)[COLS], int n);double max(double(*src)[COLS], int n);void display(double(*src)[COLS], double *rowAve, double Ave, double maxValue, int n);int main(void){double arr[ROWS][COLS];double Rave[ROWS];double rowAve, Ave, Max;int i, j;write(arr, ROWS);for (i=0; i<ROWS; i++){rowAve=rowAverage(arr, i);Rave[i]=rowAve;}Ave=average(arr, ROWS);Max=max(arr, ROWS);display(arr, Rave, Ave, Max, ROWS);printf("\n");getchar();getchar();return 0;}void write(double(*src)[COLS], int n){int i, j;for (i=0;i<ROWS; i++){printf("Please input %d rows numbers: \n", i);for (j=0; j<COLS; j++){scanf("%lf", &src[i][j]);}}}double rowAverage(double(*src)[COLS], int n) {int j;double Raverage, sum;sum=0;for (j=0; j<COLS; j++){sum +=src[n][j];}Raverage=sum/COLS;return Raverage;}double average(double(*src)[COLS], int n) {int i, j;double sum, average;sum=0;for (i=0; i<n; i++){for(j=0; j<COLS; j++){sum +=src[i][j];}}average=sum/(n*COLS);return average;}double max(double(*src)[COLS], int n){double max=0;int i, j;for (i=0; i<n; i++){for(j=0; j<COLS; j++){if (src[i][j]>max){max=src[i][j];}}}return max;}void display(double(*src)[COLS], double *rowAve, double Ave, double maxValue, int n){int i, j;printf("The array you have entered: \n");for (i=0; i<n; i++){for (j=0; j<COLS; j++){printf("%4.1lf", src[i][j]);}putchar('\n');}putchar('\n');printf("The every row average of the array you have entered: \n");for (i=0; i<n; i++){printf("%4.1f\n", rowAve[i]);}printf("The average of the array you have entered: \n");printf("%4.1f\n", Ave);printf("The max value of the array you have entered: \n");printf("%4.1f\n", maxValue);}。

面向对象的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++--primer-plus-(第6版)-中文版编程练习答案

C++--primer-plus-(第6版)-中文版编程练习答案

第二章:开始学习C++//ex2.1--display your name and address#include<iostream>int main(void){using namespace std;cout<<"My name is liao chunguang and I live in hunan chenzhou.\n”;}//ex2.2--convert the furlong units to yard uints-把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using namespace std;cout<<"enter the distance measured by furlong units:";double fur;cin>>fur;cout<<"convert the furlong to yard"<<endl;double yd;yd=fur2yd(fur);cout<<fur<<" furlong is "<<yd<<" yard"<<endl;return 0;}double fur2yd(double t){return 220*t;}//ex2.3-每个函数都被调用两次#include<iostream>void mice();void see();using namespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout<<"three blind mice"<<endl;}void see(){cout<<"see how they run"<<endl;}//ex2.4#include<iostream>int main(){using namespace std;cout<<"Enter your age:";int age;cin>>age;int month;month=age*12;cout<<age<<" years is "<<month<<" months"<<endl;return 0;}//ex2.5---convert the Celsius valve to Fahrenheit value#include<iostream>double C2F(double);int main(){using namespace std;cout<<"please enter a Celsius value:";double C;cin>>C;double F;F=C2F(C);cout<<C<<" degrees Celsius is "<<F<<" degrees Fahrenheit."<<endl;return 0;}double C2F(double t){return 1.8*t+32;}//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位#include<iostream>double convert(double);//函数原型int main(){using namespace std;cout<<"Enter the number of light years:";double light_years;cin>>light_years;double astro_units;astro_units=convert(light_years);cout<<light_years<<" light_years = "<<astro_units<<" astronomical units."<<endl; return 0;}double convert(double t){return 63240*t;//1 光年=63240 天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>void show();main(){using namespace std;show();return 0;}void show(){using namespace std;int h,m;cout<<"enter the number of hours:";cin>>h;cout<<"enter the number of minutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>const int inch_per_feet=12;// const 常量--1feet=12inches--1 英尺=12 英寸int main(){using namespace std;cout<<"please enter your height in inches:___\b\b\b";// \b 表示为退格字符int ht_inch;cin>>ht_inch;int ht_feet=ht_inch/inch_per_feet;//取商int rm_inch=ht_inch%inch_per_feet;//取余cout<<"your height is "<<ht_feet<<" feet,and "<<rm_inch<<" inches\n";return 0;}//ex3.2--计算相应的body mass index〔体重指数〕#include<iostream>const int inch_per_feet=12;const double meter_per_inch=0.0254;const double pound_per_kilogram=2.2;int main(){using namespace std;cout<<"Please enter your height:"<<endl;cout<<"First,enter your height of feet part〔输入你身高的英尺部分〕:_\b"; int ht_feet;cin>>ht_feet;cout<<"Second,enter your height of inch part〔输入你身高的英寸部分〕:_\b"; int ht_inch;cin>>ht_inch;cout<<"Now,please enter your weight in pound:___\b\b\b";double wt_pound;cin>>wt_pound;int inch;inch=ht_feet*inch_per_feet+ht_inch;double ht_meter;ht_meter=inch*meter_per_inch;double wt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Your pensonal body information as follows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass Index(体重指数) is "<<BMI<<endl;return 0;}//ex3.3 以度,分,秒输入,以度输出#include<iostream>const int minutes_per_degree=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter a latitude in degrees,minutes,and seconds:\n";cout<<"First,enter the degrees:";int degree;cin>>degree;cout<<"Next,enter the minutes of arc:";int minute;cin>>minute;cout<<"Fianlly,enter the seconds of arc:";int second;cin>>second;double show_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/mi nutes_per_degree/seconds_per_minute;cout<<degree<<" degrees,"<<minute<<" minutes,"<<second<<"seconds="<<show_in_degree<<" degrees\n";return 0;}//ex3.4#include<iostream>const int hours_per_day=24;const int minutes_per_hour=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter the number of seconds:";long seconds;cin>>seconds;int Day,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds = "<<Day<<" days,"<<Hour<<" hours,"<<Minute<<" minutes,"<<Second<<" seconds\n";return 0;}//ex3.5#include<iostream>int main(){using namespace std;cout<<"Enter the world population:";long long world_population;cin>>world_population;cout<<"Enter the population of the US:";long long US_population;cin>>US_population;double percentage;percentage=(double)US_population/world_population*100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n"; return 0;}//ex3.6 汽车耗油量-美国(mpg)or 欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the miles of distance you have driven:";double m_distance;cin>>m_distance;cout<<"Enter the gallons of gasoline you have used:";double m_gasoline;cin>>m_gasoline;cout<<"Your car can run "<<m_distance/m_gasoline<<" miles per gallon\n";cout<<"Computing by European style:\n";cout<<"Enter the distance in kilometers:";double k_distance;cin>>k_distance;cout<<"Enter the petrol in liters:";double k_gasoline;cin>>k_gasoline;cout<<"In European style:"<<"your can used "<<100*k_gasoline/k_distance<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gasoline consumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg) #include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"European style(liters per 100 kilometers):";double Euro_style;cin>>Euro_style;cout<<"Converts to U.S. style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<62.14*3.875/Euro_style<<" mpg\n";return 0;}// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Converts to U.S. style(miles per gallon):12.4 L/100Km = 19.4187 mpgPress any key to continue// ex3.7 automobile gasoline consumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n";return 0;}// Enter the automobile gasoline consumption figure inU.S. style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 12.6733L/100KmPress any key to continue第四章复合类型//ex4.1 display the information of student#include<iostream>const int Asize=20;using namespace std;struct student//定义结构描述{char firstname[Asize];char lastname[Asize];char grade;int age;};void display(student);//函数原型放在结构描述后int main(){cout<<"what is your first name?"<<endl;student lcg;//创建结构变量〔结构数据对象〕cin.getline(lcg.firstname,Asize);cout<<"what is your last name?"<<endl;cin.getline(stname,Asize);cout<<"what letter grade do you deserve?"<<endl;cin>>lcg.grade;cout<<"what is your age?"<<endl;cin>>lcg.age;display(lcg);return 0;}void display(student name){cout<<"Name: "<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2 use the string-class instead of char-array#include<iostream>#include<string>int main(){using namespace std;string name,dessert;cout<<"Enter your name: \n";getline(cin,name);cout<<"Enter your favorite dessert: \n";getline(cin,dessert);cout<<"I have some delicious "<<dessert;cout<<" for you, "<<name<<".\n";return 0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0 的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I.rdbuf()->sbumpc();//修改后的break; }ex4.3 输入其名和姓,并组合显示#include<iostream>#include<cstring>const int Asize=20;int main(){using namespace std;char fname[Asize];char lname[Asize];char fullname[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname 复制到fullname 空数组中strcat(fullname,", ");//把“,”附加到上述fullname 尾部strncat(fullname,fname,Asize);//把fname 名字附加到上述fullname 尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;}#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <cstring>const int Asize = 20;int main(){using namespace std;char firstname[Asize];char lastname[50];cout << "Enter your first name: ";cin.getline(firstname,Asize);cout << "Enter your last name: ";cin.getline(lastname,50);strcat(lastname,", ");strncat(lastname,firstname,Asize);cout << "Here's the information in a single string: "<< lastname <<endl;return 0;}//ex4.4 使用string 对象存储、显示组合结果#include<iostream>#include<string>int main(){using namespace std;string fname,lname,attach,fullname;cout<<"Enter your first name:";getline(cin,fname);//note:将一行输入读取到string 类对象中使用的是getline(cin,str) //它没有使用句点表示法,所以不是类方法cout<<"Enter your last name:";getline(cin,lname);attach=", ";fullname=lname+attach+fname;cout<<"Here's the information in a single string:"<<fullname<<endl;return 0;}//ex4.5 declare a struct and initialize it 声明结果并创建一个变量#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack={"Mocha Munch",2.3,350};cout<<"Here's the information of snack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return 0;}//ex4.6 结构数组的声明及初始化#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack[3]={{"Mocha Munch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)//利用for 循环来显示snack 变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}//ex4.7 pizza 披萨饼#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza pie;//创建一个名为pie 的结构变量cout<<"What's the name of pizza company:";cin.getline(pie pany,Size);cout<<"What's the diameter of pizza:";cin>>pie.diameter;cout<<"What's the weight of pizza:";cin>>pie.weight;cout<<"company:"<<pie pany<<endl;cout<<"diameter:"<<pie.diameter<<"inches"<<endl;cout<<"weight:"<<pie.weight<<"ounches"<<endl;return 0;}//ex4.8 pizza pie 披萨饼使用new 创建动态结构#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza *pie=new pizza;//使用new 创建动态结构cout<<"What's the diameter of pizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What's the name of pizza company:";cin.get(pie->company,Size);cout<<"What's the weight of pizza:";cin>>pie->weight;cout<<"diameter:"<<pie->diameter<<" inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<" ounches"<<endl;delete pie;//delete 释放内存return 0;}//ex.4.9 使用new 动态分配数组—方法1#include<iostream>#include<string>using namespace std;struct CandyBar{string brand;double weight;int calory;};int main(){CandyBar *snack= new CandyBar[3];snack[0].brand="A";//单个初始化由new 动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand << endl;cout << " weight: " << snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}//ex.4.10 数组—方法1#include <iostream>int main(){using namespace std;const int Size = 3;int success[Size];cout<<"Enter your success of the three times 40 meters running:\n"; cin >> success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;return 0;}//ex.4.10 array—方法2#include <iostream>#include <array>int main(){using namespace std;array<double,4>ad={0};cout<<"Enter your success of the three times 40 meters running:\n"; cin >> ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return 0;}第五章循环和关系表达式//ex.5.1#include <iostream>int main(){using namespace std;cout<<"Please enter two integers: ";int num1,num2;cin>>num1>>num2;int sum=0;for(int temp=num1;temp<=num2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl; return 0;}//ex.5.2#include <iostream>#include<array>int main(){using namespace std;array<long double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)cout<<i<<"! = "<<ad[i]<<endl;return 0;}#include <iostream>#include <array>using namespace std;int main(){array<long double, 101> multiply;multiply[0] = multiply[1] = 1LL;for (int i = 2; i <= 100; i++)multiply[i] = multiply[i-1]*i;cout << multiply[100];return 0;}//ex.5.3#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}return 0;}//ex.5.4#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo 的投资价值才能超过Daphne 的投资价值。

C++Primer(第4版)习题解答_第十章

C++Primer(第4版)习题解答_第十章

第十章关联容器1.编写程序读入一些列string和int型数据,将每一组存储在一个pair对象中,然后将这些pair对象存储在vector容器里。

// 11.16_10.1_pair.cpp : 定义控制台应用程序的入口点。

//#include"stdafx.h"#include<iostream>#include<string>#include<vector>#include<utility>using namespace std;int _tmain(int argc, _TCHAR* argv[]){string str;int iVal;cout << "\tInput some pair contents( pair<string, int > ) (^Z to end):\n";vector< pair<string, int> > pairVec;while( cin >> str >> iVal )pairVec.push_back( pair< string, int > ( str, iVal) );cout << "\n\t The content of pairVec is:\n" ;for ( vector< pair<string, int> >::iterator it = pairVec.begin(); it != pairVec.end(); ++it ){cout << it->first << " " << it->second << endl;}system("pause");return 0;}2.在前一题中,至少可使用三种方法创建pair对象。

面向对象的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,。

C++primer plus 7章—十章课后答案

C++primer plus 7章—十章课后答案

C++ Primer Plus(第六版)中文版编程练习第七章到第十八章答案7.7#include<iostream>double * fill_array( double * begin, double * end);voidshow_array( double * begin, double * end);void revalue(double factor , double * begin, double * end);using namespace std;int main(){double properties[5];double * endd=fill_array(properties,properties+5);show_array(properties,endd);double factor;cout<<"enter revaluation factor: "<<endl;cin>>factor;revalue(factor,properties,endd);show_array(properties,endd);cout<<"done";return 0;}double * fill_array( double * begin, double * end){int i;for( i=0;i<end-begin;i++){cout<<"enter value #"<<i+1<<" :"<<endl;if(!(cin>>*(begin+i)))break;}double * endd=begin+i;returnendd;}voidshow_array( double * begin, double * end){double * ps;int i;for( i=0,ps=begin;i<end-begin;i++,ps++)cout<<"value #"<<i+1<<": "<<*ps<<endl;}void revalue(double fac , double * begin, double * end) {double * ps;for(ps=begin;ps!=end;ps++){(*ps)*=fac;}}7.8a.#include<iostream>#include<string>constint Seasons=4;using namespace std;const char* snames[4]={"Spring","Summer","Fall","Winter"}; void fill(double * ps);void show(double * ps);int main(){double expense[4];fill( expense);show( expense);return 0;}void fill(double * ps){for(int i=0;i<Seasons;i++){cout<<snames[i]<<" expense: ";cin>>ps[i];}}void show(double * ps){double total=0;cout<<"expense"<<endl;for(int i=0;i<Seasons;i++){cout<<snames[i]<<" expense: "<<ps[i]<<endl;total+=ps[i];}cout<<"total expense :"<<total;}b#include<iostream>#include<string>struct inflatable{double expense[4];};inflatable expense1;constint Seasons=4;usingnamespace std;constchar* snames[4]={"Spring","Summer","Fall","Winter"};void fill(inflatable *expense1);void show(inflatable expense1);int main(){fill( &expense1);show( expense1);return 0;}void fill(inflatable *expense1){for(int i=0;i<Seasons;i++){cout<<snames[i]<<" expense: ";cin>>(*expense1).expense[i];}}void show(inflatable expense1){double total=0;cout<<"expense"<<endl;for(int i=0;i<Seasons;i++){cout<<snames[i]<<" expense: "<<expense1.expense[i]<<endl;total+=expense1.expense[i];}cout<<"total expense :"<<total;}7.9#include<iostream>usingnamespace std;constint SLEN=30;struct student{char fullname[SLEN];char hobby[SLEN];int ooplevel;};int getinfo(student pa[],int n);void display1(student st);void display2(const student * ps);void display3(const student pa[],int n);int main(){cout<<"enter class size: ";int class_size;cin>>class_size;while(cin.get()!='\n')continue;student * ptr_stu=new student[class_size];int entered=getinfo(ptr_stu,class_size);for(int i=0;i<entered;i++){display1(ptr_stu[i]);display2(&ptr_stu[i]);}display3(ptr_stu,entered);delete ptr_stu;cout<<"Done\n";return 0;}int getinfo(student pa[],int n){int count=0;for(int i=0;i<n;i++){cout<<"\nstudent "<<i+1<<endl;cout<<"fullname: ";cin>>pa[i].fullname;cout<<"hobby: ";cin>>pa[i].hobby;cout<<"ooplevel: ";cin>>pa[i].ooplevel;count++;}cout<<"\nenter end!";return count;}void display1(student st){cout<<"\nfullname: "<<st.fullname<<endl;cout<<"hobby: "<<st.hobby<<endl;cout<<"ooplevel: "<<st.ooplevel<<endl;}void display2(const student * ps){cout<<"fullname: "<<(*ps).fullname<<endl;cout<<"hobby: "<<(*ps).hobby<<endl;cout<<"ooplevel: "<<(*ps).ooplevel<<endl;}void display3(const student pa[],int n){for(int i=0;i<n;i++){cout<<"student "<<i+1<<endl;cout<<"fullname: "<<(pa[i]).fullname<<endl;cout<<"hobby: "<<(pa[i]).hobby<<endl;cout<<"ooplevel: "<<(pa[i]).ooplevel<<endl;}}7.10#include<iostream>double add(double x,double y);double calculate(double x,double y,double (*pf)(double,double)); double multiply(double x,double y);double minus(double x,double y);usingnamespace std;int main(){double x,y;cout<<"enter two numbers: "<<endl;while(cin>>x>>y){double ( *pf[3])(double x,double y)={add,multiply,minus};for(int i=0;i<3;i++){cout<<"result: "<<i+1<<": "<<calculate(x,y,pf[i]);cout<<endl;}}cout<<"done!";return 0;}double calculate(double x,double y,double (*pf)(double,double)) {double n=(*pf)(x,y);return n;}double add(double x,double y){return x+y;}double multiply(double x,double y){return x*y;}double minus(double x,double y){return x-y;}8.1#include<iostream>#include<string>usingnamespace std;int count=0;void show(constchar * str,int n =0);int main(){show("hello");show("can i make friends with you");show("sorry",2);show("excuse");cout<<"done!";return 0;}void show(constchar * str,int n ){if(n==0)cout<<str<<endl;else{for(int i=0;i<count;i++)cout<<str<<endl;}count++;}8.2#include<iostream>usingnamespace std;struct candy{char *name;double weight;int heat;};void set_arr(candy & candy1,char * ps="Millennium Munch",double w=2.85,int heat=350); void show(const candy & candy1);int main(){candy tu={"tutu",2.96,36};show(tu);set_arr(tu);set_arr(tu,"cuicui",2.96,400);show(tu);return 0;}void set_arr(candy & candy1,char * ps,double w,int heat){=ps;candy1.weight=w;candy1.heat=heat;show(candy1);}void show(const candy & candy1)\{cout<<"name: "<<<<endl;cout<<"weight: "<<candy1.weight<<endl;cout<<"heat: "<<candy1.heat<<endl;}8.3#include<iostream>#include<string>#include<cctype>usingnamespace std;void change(string &str);int main(){string str;cout<<"enter a string (q to quit): "; getline(cin,str);while(str!="q"){change( str);cout<<"\nnext string (q to quit): ";getline(cin,str);}cout<<"bye!";return 0;}void change(string &str){int size=str.size();for(int i=0;i<size;i++){str[i]=toupper(str[i]);}cout<<str;}8.4#include<iostream>#include<cstring>#include<string>usingnamespace std;struct stringy{char * str;int ct;};void show(const stringy &stru,int n=1);void show(constchar str[]="Done!",int m=1);void set(stringy & a, constchar arr[] );int main(){stringy beany;char testing[]="Reality isn't what it used to be.";set(beany,testing);show(beany);show(beany,2);testing[0]='d';testing[1]='u';show(testing);show(testing,3);show();return 0;}void show(const stringy &stru,int n){for(int i=0;i<n;i++)cout<<"\nstring member: "<<stru.str;}void show(constchar str[],int m){for(int i=0;i<m;i++)cout<<"\ntesting string: "<<str;}void set(stringy & a, constchar arr[] ){int size=strlen(arr);a.str=newchar[size+1];strcpy(a.str,arr);a.ct=size;cout<<"\nsize of string: "<<a.ct;}8.5#include<iostream>template<class T> T max5(T arr[5]);int main(){usingnamespace std;double arr[5]={1.23,3.65,2.54,9.65,7.56};int arr1[5]={2,6,46,89,64};cout<<"result:"<<endl;max5(arr);cout<<"\nanother result:"<<endl;max5(arr1);cout<<"\ndone!";return 0;}template<class T> T max5(T arr[5]){usingnamespace std;T max=arr[0];for(int i=0;i<5;i++){if(arr[i]>max)max=arr[i];}cout<<"max:"<<max;return max;}8.6#include<iostream>#include<cstring>usingnamespace std;template<class T> T maxn(T arr[],int n);template<>char* maxn(char* ps[],int n);int main(){int arr[6]={6,9,56,48,2,13};double arr1[4]={8.63,5.69,6.12,4.65};char * ps[3]={"xiaokai","xuman","xiaochen"};cout<<"result:"<<endl;maxn(arr,6);cout<<"\nanother result:"<<endl;maxn(arr1,4);maxn(ps,3);cout<<"\ndone!";return 0;}template<class T> T maxn(T arr[],int n){usingnamespace std;T max=arr[0];for(int i=0;i<n;i++){if(arr[i]>max)max=arr[i];}cout<<"max:"<<max;return max;}template<>char* maxn(char* ps[],int n){char * str=ps[0];for(int i=0;i<n;i++){if(strlen(str) <strlen(ps[i]))str=ps[i];}cout<<"\naddress: "<<str;return str;}8.7#include<iostream>struct debts{char name[50];double amount;};usingnamespace std;template<class T> T sumarray(T arr[],int n); template<class T> T sumarray(T * ps[],int n);int main(){int things[6]={13,31,103,301,310,130};struct debts mr_E[3]={{"ima wolfe",2400.0},{"ura foxe",1300.0},{"iby stout",1800.0}};double *pd[3];for(int i=0;i<3;i++){pd[i]=&mr_E[i].amount;}cout<<"sum of thing: "<<sumarray(things,6)<<endl;cout<<"sum of debt: "<<sumarray(pd,3)<<endl;cout<<"\ndone!";return 0;}template<class T> T sumarray(T arr[],int n){T total=0;for(int i=0;i<n;i++)total+=arr[i];return total;}template<class T> T sumarray(T * ps[],int n){T total=0;for(int i=0;i<n;i++){total+=*ps[i];}return total;}9.1golf.hconstint Len=40;struct golf{char fullname[Len];int handicap;};void setgolf(golf & g, constchar* name, int hc);int setgolf (golf & g);void handicap(golf &g,int hc);void showgolf(const golf & g);golf.cpp#include<iostream>#include"golf.h"#include<cstring>usingnamespace std;int setgolf (golf & g){cout<<"fullname: ";cin.getline(g.fullname,Len);if(g.fullname[0]=='\0')return 0;cout<<"handicap: ";cin>>g.handicap;cin.get();cout<<"done!";return 1;}void setgolf(golf & g, constchar* name, int hc){strcpy(g.fullname,name);g.handicap=hc;}void handicap(golf &g,int hc){cout<<"reset new value: "<<endl;g.handicap=hc;}void showgolf(const golf & g){cout<<"\nfullname: "<<g.fullname<<endl;cout<<"handicap: "<<g.handicap<<endl;}main.cpp#include<iostream>#include"golf.h"usingnamespace std;int main(){cout<<"enter golf struct :"<<endl;golfann[3];for(int i=0;i<3;i++){golfandy;cout<<"\n# "<<i+1<<": "<<endl;int num=setgolf(andy);if(num){setgolf(ann[i],andy.fullname,andy.handicap);showgolf(ann[i]);}elsebreak;}cout<<"all done!"<<endl;cout<<"reset a new value: ";int hc;cin>>hc;cin.get();cin.clear();handicap(ann[0],hc);showgolf(ann[0]);cin.get();return 0;}9.2#include<iostream>#include<string>usingnamespace std;void strcount(const string str);int main(){string input;cout<<"enter a line: \n";while(getline(cin,input)){if(input==””)break;strcount(input);cout<<"enter next line (empty line to quit):\n";}cout<<"bye\n";return 0;}void strcount(const string str){staticint total =0;int count=0;cout<<"\""<<str<<"\" contains ";count=str.size();total+=count;cout<<count<<" characters\n";cout<<total<<" characters total\n";}#include<iostream>#include<cstring>#include<new>struct chaff{char dross[20];int slag;};void showstruct( chaff & s);void setstruct(chaff & s);usingnamespace std;char buffer1[500];int main(){chaff * p;p=new (buffer1) chaff [2];for(int i=0;i<2;i++){cout<<"\n#"<<i+1<<":";setstruct(p[i]);showstruct(p[i]);}cout<<"\ndone!";delete [] p;return 0;}void showstruct( chaff & s){cout<<"\nshow!";cout<<"\ndross: ";cout<<s.dross;cout<<"\nslag: ";cout<<s.slag;}void setstruct(chaff & s){cout<<"\nvalue of dross has been automatically set.";strcpy(s.dross,"hello");cout<<"\nslag: ";cin>>s.slag;}account.h#include<string>#include<iostream>class bankaccount{private:std::string name;char acctnum[20];double savings;public:bankaccount(const std::string & co, constchar * num,double n);~bankaccount();void show()const;void depoit(double num);void takeout(double n);};account.cpp#include"account.h"#include<cstring>bankaccount::bankaccount(const std::string & co, constchar * num,double n) {name=co;strcpy(acctnum,num);savings=n;}bankaccount::~bankaccount(){}void bankaccount::show()const{using std::cout;cout<<"\nname: "<<name;cout<<"\naccountnumber: "<<acctnum;cout<<"\nsavings: "<<savings;}void bankaccount:: depoit(double n){savings+=n;}void bankaccount:: takeout(double n){savings-=n;}main.cpp#include<iostream>#include"account.h"int main(){using std::cout;using std::cin;bankaccount user=bankaccount("xiaozhao","xiaoxing",0.0);user.show();user.depoit(100);user.show();user.takeout(30);user.show();cout<<"\ndone!";cin.get();cin.get();return 0;}10.2name.h#include<iostream>#include<string>class person{private:staticconstint LIMIT=25;std::stringlname;char fname[LIMIT];public:person(){lname="";fname[0]='\0';};person(const std::string &ln,constchar * fn="Heyyou");void show() const;void formalshow() const;};name1.cpp#include<iostream>#include"name.h"#include<cstring>person::person(const std::string &ln,constchar * fn){lname=ln;strcpy(fname,fn);}void person:: show() const{using std::cout;cout<<"\nfirstname: "<<fname;cout<<"\nlastname: "<<lname; }void person:: formalshow() const{using std::cout;cout<<"\nlastname: "<<lname; cout<<"\nfirstname: "<<fname;}main.cpp#include<iostream>#include"name.h"using std::cout;using std::endl;using std::cin;int main(){person one;person two("Smythecraft");person three("Dimwiddy","Sam");one.show();cout<<endl;one.formalshow();cout<<"\ndone!";two.show();cout<<endl;two.formalshow();cout<<"\ndone!";three.show();cout<<endl;three.formalshow();cout<<"\ndone!";cin.get();return 0;}10.4sale.hnamespace sales{class sale{staticconstint QUARTER=4;private:double sale1[QUARTER];double average;double max;double min;public:sale();sale(double ar[]);void showsale();};};sale.cpp#include<iostream>#include"sale.h"#include<cstring>namespace sales{sale:: sale(){using std::cout;using std::cin;cout<<"\ninput four sales: ";double ar[4];double total=0;double max1=-999;double min1=999;for(int i=0;i<4;i++){cout<<"\n# "<<i+1<<": ";cin>>ar[i];total+=ar[i];if(max1<ar[i])max1=ar[i];if(min1>ar[i])min1=ar[i];}for(int i=0;i<4;i++)sale1[i]=ar[i];average=total/4;max=max1;min=min1;}sale:: sale( double ar[]){using std::cout;using std::cin;double total=0;double max1=-999;double min1=999;for(int i=0;i<4;i++){total+=ar[i];if(max1<ar[i])max1=ar[i];if(min1>ar[i])min1=ar[i];}average=total/4;max=max1;min=min1;}void sale:: showsale(){using std::cout;using std::endl;cout<<"\naverage: "<<average;cout<<"\nmax: "<<max;cout<<"\nmin: "<<min<<endl;}};main.cpp#include<iostream>#include"sale.h"usingnamespace sales;int main(){usingnamespace std;cout<<"\nstart";sale one=sale();one.showsale();cin.get();cin.get();cout<<"\nnext";double att[4]={20.1,30.1,50.1,60.1};sale two=sale(att);two.showsale();cout<<"\nall done!";cin.get();cin.get();return 0;}10.5stack.hstruct customer{char fullname[35];double payment;};typedef customer Item;class stack{private:enum{MAX=10};Item items[MAX];int top;public:stack();bool isempty() const;bool isfull() const;bool push(const Item & item);bool pop(Item & item);};stack.cpp#include<iostream>#include"stack.h"stack::stack(){top=0;}bool stack:: isempty() const{return top==0;}bool stack::isfull() const{return top==MAX;}bool stack:: push(const Item & item) {if (top<MAX){items[top++]=item;returntrue;}elsereturnfalse;}bool stack:: pop(Item & item){if (top>0){item=items[--top];returntrue;}elsereturnfalse;}main.cpp#include<iostream>#include"stack.h"staticdouble total=0;int main(){usingnamespace std;Item one[5]={{"xiao wang",20},{"xiao hong",30},{"xiao li",50},{"xiao liu",80},{"xiao zhao",100}};stackst;if(st.isempty())cout<<"stack already empty\n";for(int i=0;i<5;i++){st.push(one[i]);cout<<"\n#"<<i+1<<endl;cout<<"fullname: "<<one[i].fullname<<" "<<"payment: "<<one[i].payment;};cout<<"\nonece again!";for(int i=0;i<5;i++){st.push(one[i]);cout<<"\n#"<<i+1<<endl;cout<<"fullname: "<<one[i].fullname<<" "<<"payment: "<<one[i].payment;};Item three[10];if(st.isfull())cout<<"\nstack already full";for(int i=0;i<10;i++){st.pop(three[i]);total+=three[i].payment;}cout<<"\ntotal: "<<total;if(st.isempty())cout<<"\nstack already empty!";elsecout<<"\nstack is not empty!";cin.get();return 0;}10.6move.hclass move{private:double x;double y;public:move(double a=0,double b=0);void showmove() const;move add(const move & m) ;void reset (double a,double b);};move.cpp#include"move.h"#include<iostream>move:: move(double a,double b){x=a;y=b;}void move:: showmove() const{using std::cout;cout<<"\nshow ";cout<<"\nx value: "<<x;cout<<"\ny value: "<<y;}move move:: add(const move & m){x+=m.x;y+=m.y;return *this;}void move:: reset (double a,double b) {x=a;y=b;}main.cpp#include<iostream>#include"move.h"int main(){using std::cin;move one=move();one.showmove();one.reset(20,30);one.showmove();move two=one.add(one);two.showmove();cin.get();cin.get();return 0;}10.7plorg.hclass plorg{private:char name[20];int CI;public:plorg(constchar names[20]="Plorga",int n=50);void setvalue(int m);void show() const;};plorg.cpp#include<iostream>#include"plorg.h"#include<cstring>plorg:: plorg(constchar names[20],int n){strcpy(name,names);CI=n;}void plorg:: setvalue(int m){CI=m;}void plorg:: show() const{using std::cout;cout<<"\nshow";cout<<"\nname: "<<name;cout<<"\nCI: "<<CI;}main.cpp#include<iostream>#include"plorg.h"int main(){usingnamespace std;plorg one=plorg("wang", 5);plorg two=plorg();one.show();one.setvalue(10);one.show();two.show();cin.get();cin.get();return 0;}。

《C++程序设计教程》第二版 第10章 类和对象

《C++程序设计教程》第二版 第10章 类和对象
}
13
类和对象
[例10.4] 定义并测试长方形类Crect, 长方形是由左上角坐标(left, top) 和右下角坐标(right, bottom)组成。 (left, top) ●
● (right, bottom)
见 “第10章 类和对象(例子).doc”
14
10.1.5
对象的存储空间
类和对象
5
类和对象
类是一种类型,该类型的变量称为对象(实例) 对象的定义: <类名> <对象列表>;
如:Person a, b ;
// 定义a、b两个对象
可以定义对象的指针和对象数组: 如:Person *pa, *pb, x[10]; // pa和pb是两个Person类型指针, x是对象数组 pa=&a; pa=x; pb=&b; pb=x; 那么能否这样访问对象a的成员呢? , a.Sex, a.Age 回答是:不能!
17
类和对象
10.1.6 定义类和对象的有关说明(续)
3.定义对象的三种方法 :
(1)类的定义完成后,定义对象 class A // A类的定义 { int x; double y; public: ...... }; A a1, a2, a3; //定义A类对象
18
类和对象
10.1.6 定义类和对象的有关说明(续) (2)在定义类的同时定义对象 class A // A类的定义 { int x; float y; public: ...... } a1, a2, a3; //定义A类对象
21
类和对象
如何理解类、如何理解对象

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

1.account.h#ifndef ACCOUNT_H_#define ACCOUNT_H_#include<string>class BankAccount{private:std::string name;std::string account_m;double saving;public:BankAccount(const std::string & client, const std::string & num, double pr = 0.0);void show() const;void despoit(double pr);void withdraw(double pr);};#endifaccount.cpp#include<iostream>#include"account.h"BankAccount::BankAccount(const std::string & client, const std::string &num, double pr ){name = client;account_m = num;saving = pr;}void BankAccount::show() const{std::cout << "BankAccount : " << std::endl;std::cout << "Name is: " << name << " , Account: " << account_m << " , Saving: " << saving << " . " << std::endl;}void BankAccount::despoit(double pr) //存ä?款?{saving = pr + saving;}void BankAccount::withdraw(double pr) //取¨?款?{if(pr > saving)std::cout << "There is not so much money." << std::endl;elsesaving = saving - pr;}Main.cpp#include<iostream>#include"account.h"const int STAK = 2;int main(){BankAccount acc1("Hello", "123", 1200.0);BankAccount acc2("Good", "234",1100.0);acc1.show();acc2.show();std::cout << "Add money to acc1." << std::endl; //存ä?款?acc1.despoit(200.0);acc1.show();std::cout << "Apart money from acc2. " << std::endl;//取¨?款?acc2.withdraw(100.0);acc2.show();return 0;}2.头文件#ifndef STACK_H_#define STACK_H_#include <string>class Person{private:static const int LIMIT = 25;std::string lname;char fname[LIMIT];public:Person() {lname = "", fname[0] = '\0';}Person(const std::string & ln, const char * fn = "Heyyou");void show()const;void Formalshow()const;};#endif定义#include <iostream>#include <string>#include "stack.h"Person::Person(const std::string & ln, const char * fn ){lname = ln;strcpy(fname,fn);}void Person::show()const{std::cout << "The last name: " << lname << " ,The first name: " << fname << std::endl;}void Person::Formalshow()const{std::cout << "The first name: " << fname<< " ,The last name: " <<lname <<std::endl;}主函数#include <iostream>#include "stack.h"int main(){Person one;Person two("Good");Person three("Hello","Hi");one.show();std::cout << std::endl;one.Formalshow();std::cout << std::endl;two.show();std::cout << std::endl;two.Formalshow();std::cout << std::endl;three.show();std::cout << std::endl;three.Formalshow();std::cout << std::endl;return 0;}3.头文件#ifndef GOLF_H_#define GOLF_H_#include <string>class Golf{private:std::string fullname;int handicap;public:Golf(const std::string & fu, int ha);const Golf & setgolf(const Golf & g);void show()const;};#endif定义#include <iostream>#include <string>#include "golf.h"Golf::Golf(const std::string & fu, int ha) {fullname = fu;handicap = ha;}const Golf & Golf::setgolf(const Golf & g) {fullname = g.fullname;handicap = g.handicap;return * this;}void Golf::show()const{using std::cout;using std::endl;cout <<"Fullname: " << fullname << " ,Handicap: " << handicap << endl;}主函数#include <iostream>#include "golf.h"int main(){Golf golf1("Hello", 123);golf1.show();Golf golf2("Great", 345);golf2.show();golf1.setgolf(golf2);golf1.show();return 0;}4.头文件#ifndef GOLF_H_#define GOLF_H_namespace SALES{const int QUARTERS = 4;class Sales{private:double sales[QUARTERS];double average;double max;double min;public:Sales();Sales(const double ar[], int n);void setsales();void showsales()const;};}#endif定义#include <iostream>#include "golf.h"namespace SALES{using std ::cout;using std ::cin;using std ::endl;static double salesaverage(const double arr[], int arrsize)double sum = 0;for(int i = 0; i < arrsize; i++)sum += arr[i];return (sum/arrsize);}static double salesmax(const double arr[], unsigned arrsize) {double max = arr[0];for (int i =1; i < arrsize; i++){if(max < arr[i])max = arr[i];elsemax;}return max;}static double salesmin(const double arr[], unsigned arrsize) {double min = arr[0];for (int i =1; i < arrsize; i++){if(min > arr[i])min = arr[i];elsemin;}return min;Sales::Sales(){for(int i = 0; i < QUARTERS; i++)sales[i] = 0;average = 0;max = 0;min = 0;}Sales::Sales(const double ar[], int n){unsigned times = n < QUARTERS ? (unsigned) n:QUARTERS;for (int i = 0; i < times; i++)sales[i] = ar[i];for (int i = times; i < QUARTERS; i++)sales[i] = 0;average = salesaverage(sales, times);max = salesmax(sales, times);min = salesmin(sales, times);}void Sales::setsales(){cout << "Enter 4 sales: " << endl;for (int i = 0; i < QUARTERS; i++){cout << "# " << i+1 << " : ";cin >> sales[i];}average = salesaverage(sales, QUARTERS);max = salesmax(sales, QUARTERS);min = salesmin(sales, QUARTERS);}void Sales::showsales()const{cout << "Sales: " << endl;for (int i = 0; i < QUARTERS; i++){cout << "# " << i+1 << " : " << sales[i] <<endl;}cout << "average: " << average << endl;cout << "max: " << max << endl;cout << "min: " << min << endl;}}主函数#include <iostream>#include "golf.h"int main(){using namespace SALES;Sales A;double hc[4] = {1.2, 2.3, 3.4, 4.5};Sales Sales1(hc, sizeof(hc)/sizeof(hc[0]));Sales1.showsales();Sales Sales2;Sales2.setsales();Sales2.showsales();return 0;}5.头文件#ifndef STACK_H_#define STACK_H_struct customer{char fullname[35];double payment;};typedef customer Item;class Stack{private:enum { MAX = 10};Item item[MAX];int top;public:Stack();bool isempty() const;bool isfull() const;bool push(const Item & items);};#endif定义#include <iostream>#include "stack.h"Stack::Stack(){top = 0;}bool Stack::isempty() const{return top == 0;}bool Stack::isfull() const{return top == MAX;}bool Stack::push(const Item & items) {if(top < MAX){item[top++] = items;return true;}elsereturn false;}{if(top > 0){items = item[--top];return true;}elsereturn false;}主函数#include <iostream>#include "stack.h"void get_customer(customer & cu);int main(){using namespace std;Stack st;customer temp;char ch;double payment = 0;cout << "Enter A, P, Q." << endl;while(cin >> ch && toupper(ch) != 'Q'){while(cin.get() != '\n')continue;if(!isalpha(ch)){cout << '\a';continue;}switch(ch){case'A':case'a': cout << "Enter a coustomer to add: " << endl;get_customer(temp);if(st.isfull())cout << "It is full." << endl;elsest.push(temp);break;case'P':case'p': if(st.isempty())cout << "It is empty." << endl;else{st.pop(temp);payment = payment + temp.payment;cout << "The total payment is $ " << payment << endl;}break;}cout << "Enter A, P, Q." << endl;}cout << "Done!" << endl;return 0;}void get_customer(customer & cu){using namespace std;cout << "Enter a fullname: " ;cin.getline(cu.fullname, 35);cout << "Enter a payment: ";cin >> cu.payment ;}6.主函数#ifndef STACK_H_#define STACK_H_class Move{private:double x;double y;public:Move(double a = 0, double b = 0);void showmove() const;Move add(const Move & m)const;void reset(double a = 0, double b = 0); };#endif定义#include <iostream>#include "stack.h"Move::Move(double a, double b){x = a;y = b;}void Move::showmove() const{std::cout << "x: " << x ;std::cout << " , y: " << y << std::endl; }Move Move::add(const Move & m)const {Move temp;temp.x = x + m.x;temp.y = y + m.y;return temp;}void Move::reset(double a , double b ){x = a;y = b;}主函数#include <iostream>#include "stack.h"int main(){using namespace std;Move mo1;mo1.showmove();Move mo2(2.0, 3.0);mo2.showmove();Move mo3(3.0, 4.0);mo3.showmove();mo1 = mo3.add(mo2);mo1.showmove();mo1.reset();mo1.showmove();return 0;}7.头文件ifndef STACK_H_#define STACK_H_class Plorg{private:char name[19];int CI;public:Plorg(); // 默?认¨?函¡¥数ºyPlorg(char * na, int ci = 50); //更¨¹改?函¡¥数ºyvoid Change(int ci);void showplorg()const;};#endif定义#include <iostream>#include "stack.h"Plorg::Plorg() //默?认¨?{strcpy(name, "Plorga");CI = 0;}Plorg::Plorg(char * na, int ci ) //新?名?称?{strcpy(name, na);CI = ci;}void Plorg::Change(int ci) //交?换?不?需¨¨要°a返¤¦Ì回?值¦Ì{CI = ci;}void Plorg::showplorg()const{std::cout << "Plorg: " << std::endl;std::cout << "Name: " << name << std::endl;std::cout << "CI: " << CI << std::endl;}主函数#include <iostream>#include "stack.h"int main(){using namespace std;Plorg p1;p1.showplorg();p1.Change(25);p1.showplorg();Plorg p2("Hello");p2.showplorg();return 0;}8.头文件#ifndef LIST_H_#define LIST_H_const int LIMIT = 50; struct Hello{char name[LIMIT];int rat;};typedef Hello Item;class List{private:enum { MAX = 10};Item items[MAX];int top;public:List();bool isempty() const;bool isfull() const;bool push(const Item & item);bool pop(Item & item);void visit(void (*pf)(Item &)); };#endif定义#include <iostream>#include "list.h"List::List(){top = 0;}bool List::isempty() const{return top == 0;}bool List::isfull() const{return top == MAX;}bool List::push(const Item & item) {if(top < MAX){items[top++] = item;return true;}elsereturn false;}bool List::pop(Item & item){if(top > 0){item = items[--top];return true;}elsereturn false;}void List::visit(void (*pf)(Item &)) {for(int i = 0; i < top; i++)(*pf)(items[i]);}主函数#include <iostream>#include "list.h"void add(Hello & h);void show(Item & item);int main(){using namespace std;List li;char ch;Hello he;cout << "Enter A, P, Q: " << endl;while(cin >> ch && toupper(ch) != 'Q'){while(cin.get() != '\n')continue;switch(ch){case'A':case'a': cout << "Enter a he. " << endl;add(he);if(li.isfull())cout << "Full" <<endl;elseli.push(he);break;case'p':case'P': if(li.isempty())cout << "Empty" <<endl;else{li.visit(show);li.pop(he);}break;}cout << "Enter A, P, Q: " << endl;}cout << "Bye!" << endl;return 0;}void add(Hello & h){std::cout << "Enter a name. " << std::endl;std::cin.getline(, LIMIT);std::cout << "Enter a rat. " << std::endl;std::cin >> h.rat;}void show(Item & item){std::cout << "Name: " << << std::endl;std::cout << "Rat: " << item.rat << std::endl;}。

相关文档
最新文档