C++ - Primer - Plus(第五版)习题解答

更新时间:2024-06-24 09:08:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

Chapter 2

// pe2-2.cpp

#include

int main(void) {

using namespace std;

cout << \ double furlongs; cin >> furlongs; double feet;

feet = 220 * furlongs;

cout << furlongs << \ << feet << \

return 0; }

// pe2-3.cpp

#include using namespace std;

void mice(); void run(); int main() {

mice(); mice(); run(); run();

return 0; }

void mice() {

cout << \}

void run() {

cout << \}

// pe2-4.cpp

#include

double C_to_F(double); int main() {

using namespace std;

cout << \ double C; cin >> C; double F;

SP 1 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

F = C_to_F(C);

cout << C << \ << F << \

return 0; }

double C_to_F(double temp) {

return 1.8 * temp + 32.0; }

Chapter 3

// pe3-1.cpp

#include

const int Inch_Per_Foot = 12;

int main(void) {

using namespace std;

// Note: some environments don't support the backspace character cout << \ int ht_inch; cin >> ht_inch;

int ht_feet = ht_inch / Inch_Per_Foot; int rm_inch = ht_inch % Inch_Per_Foot;

cout << \ cout << rm_inch << \ return 0; }

// pe3-3.cpp

#include

const double MINS_PER_DEG = 60.0; const double SECS_PER_MIN = 60.0; int main() {

using namespace std;

int degrees; int minutes; int seconds;

double latitude;

cout << \ cout << \ cin >> degrees;

cout << \ cin >> minutes;

cout << \ cin >> seconds;

latitude = degrees + (minutes + seconds / SECS_PER_MIN)/MINS_PER_DEG; cout << degrees << \ << seconds << \ return 0; }

SP 2 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// pe3-5.cpp

#include

int main(void) {

using namespace std;

cout << \ float miles; cin >> miles;

cout << \ float gallons; cin >> gallons;

cout << \ cout << \ return 0; }

// pe3-6.cpp

#include

const double KM100_TO_MILES = 62.14; const double LITERS_PER_GALLON = 3.875;

int main ( void ) {

using namespace std; double euro_rating; double us_rating;

cout << \ cin >> euro_rating;

// divide by LITER_PER_GALLON to get gallons per 100-km // divide by KM100_TO_MILES to get gallons per mile // invert result to get miles per gallon

us_rating = (LITERS_PER_GALLON * KM100_TO_MILES) / euro_rating; cout << euro_rating << \ cout << us_rating << \

return 0; }

Chapter 4

// pe4-2.cpp -- storing strings in string objects #include #include int main() {

using namespace std; string name; string dessert;

cout << \

getline(cin, name); // reads through newline cout << \ getline(cin, dessert);

cout << \ cout << \ return 0; }

SP 3 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// pe4-3.cpp -- storing strings in char arrays #include #include const int SIZE = 20; int main() {

using namespace std; char firstName[SIZE]; char lastName[SIZE];

char fullName[2*SIZE + 1];

cout << \ cin >> firstName;

cout << \ cin >> lastName;

strncpy(fullName,lastName,SIZE); strcat(fullName, \

strncat(fullName, firstName, SIZE); fullName[SIZE - 1] = '\\0';

cout << \ << fullName << endl; return 0; }

// pe4-5.cpp

// a candybar structure struct CandyBar { char brand[40]; double weight; int calories; };

#include

int main() {

using namespace std; //introduces namespace std CandyBar snack = { \

cout << \ cout << \

cout << \

return 0; }

// pe4-7.ccp

#include

const int Slen = 70;

struct pizza {

char name[Slen]; float diameter; float weight; };

int main(void)

SP 4 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

{

using namespace std; pizza pie;

cout << \ cin.getline(pie.name, Slen);

cout << \ cin >> pie.diameter;

cout << \ cin >> pie.weight;

cout << \

cout << \ cout << \ return 0; }

Chapter 5

// pe5-2.cpp

#include

int main(void) {

using namespace std; double sum = 0.0; double in;

cout << \ cin >> in;

while (in != 0) { sum += in;

cout << \

cout << \ cin >> in; }

cout << \ return 0; }

// pe5-4.cpp // book sales

#include

const int MONTHS = 12;

const char * months[MONTHS] = {\ \ \int main() {

using namespace std; //introduces namespace std int sales[MONTHS]; int month;

cout << \ for (month = 0; month < MONTHS; month++) {

cout << \ cin >> sales[month]; }

SP 5 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

double total = 0.0;

for (month = 0; month < MONTHS; month++) total += sales[month];

cout << \ return 0; }

// pe5-6.cpp

#include

struct car { char name[20]; int year;};

int main(void) {

using namespace std; int n;

cout << \

cin >> n;

while(cin.get() != '\\n') // get rid of rest of line ;

car * pc = new car [n];

int i;

for (i = 0; i < n; i++) {

cout << \ cout << \ cin.getline(pc[i].name,20);

cout << \ cin >> pc[i].year;

while(cin.get() != '\\n') // get rid of rest of line ; }

cout << \ for (i = 0; i < n; i++)

cout << pc[i].year << \

delete [] pc; return 0; }

// pe5-7.cpp -- count words using C-style string

#include

#include // prototype for strcmp() const int STR_LIM = 50; int main() {

using namespace std; char word[STR_LIM]; int count = 0;

cout << \

while (cin >> word && strcmp(\

SP 6 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

++count;

cout << \ return 0; }

// pe5-9.cpp //nested loops

#include

int main() {

using namespace std; //introduces namespace std int rows; int row; int col;

int periods;

cout << \ cin >> rows;

for (row = 1; row <= rows; row++) {

periods = rows - row;

for (col = 1; col <= periods; col++) cout << '.';

// col already has correct value for next loop for ( ; col <= rows; col++) cout << '*'; cout << endl; }

return 0; }

Chapter 6

// pe6-1.cpp

#include #include int main( ) {

using namespace std; //introduces 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;

SP 7 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

}

// pe6-3.cpp

#include

int main(void) {

using namespace std;

cout << \ cout << \ << \ char ch; cin >> ch;

while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g') {

cout << \ cin >> ch; }

switch (ch) {

case 'c' : cout << \ break;

case 'p' : cout << \ break;

case 't' : cout << \ break;

case 'g' : cout << \ break;

default : cout << \ }

return 0; }

// pe6-5.cpp

// Neutronia taxation #include

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; double tax;

cout << \ 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); else

tax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2) + RATE3 * (income - LEV3);

SP 8 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

cout << \

return 0; }

// pe6-7.cpp

#include #include int main() {

using namespace std; string word; char ch;

int vowel = 0;

int consonant = 0; int other = 0;

cout << \ cin >> word;

while ( word != \ {

ch = tolower(word[0]); if (isalpha(ch)) {

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowel++; else

consonant++; } else

other++; cin >> word; }

cout << vowel <<\

cout << consonant << \ cout << other << \

return 0; }

// pe6-8.cpp -- counting characters #include

#include // file I/O suppport #include // support for exit() const int SIZE = 60; int main() {

using namespace std; char filename[SIZE]; char ch;

ifstream inFile; // object for handling file input

cout << \ cin.getline(filename, SIZE);

inFile.open(filename); // associate inFile with a file if (!inFile.is_open()) // failed to open file {

cout << \ cout << \ exit(EXIT_FAILURE); }

int count = 0; // number of items read

SP 9 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

inFile >> ch; // get first value

while (inFile.good()) // while input good and not at EOF {

count++; // one more item read inFile >> ch; // get next value }

cout << count << \

inFile.close(); // finished with the file return 0; }

Chapter 7

//pe7-1.cpp -- harmonic mean

#include

double h_mean(double x, double y);

int main(void) {

using namespace std; double x,y;

cout << \ while (cin >> x >> y && x * y != 0)

cout << \ << y << \/* or do the reading and testing in two parts: while (cin >> x && x != 0) {

cin >> y; if (y == 0) break; ... */

cout << \ return 0; }

double h_mean(double x, double y) {

return 2.0 * x * y / (x + y); }

// pe7-3.cpp

#include

struct box {

char maker[40]; float height; float width; float length; float volume; };

SP 10 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

void showbox(box b); void setbox(box * pb);

int main(void) {

box carton = {\ setbox(&carton); showbox(carton); return 0; }

void showbox(box b) {

using namespace std;

cout << \ << \ << \ << \

<< \}

void setbox(box * pb) {

pb->volume = pb->height * pb->width * pb->length; }

// pe7-4.cpp -- probability of winning #include

long double probability(unsigned numbers, unsigned picks);

int main() {

using namespace std; double total, choices; double mtotal;

double probability1, probability2;

cout << \ \ while ((cin >> total >> choices) && choices <= total) {

cout << \ \ if (!(cin >> mtotal)) break;

cout << \\

<< (probability1 = probability(total, choices) ) << \ cout << \ << (probability2 = probability(mtotal, 1) ) << \ cout << \

cout << probability1 * probability2; // compute the probability cout << \

cout << \ }

cout << \ return 0; }

// the following function calculates the probability of picking picks // numbers correctly from numbers choices

long double probability(unsigned numbers, unsigned picks) {

long double result = 1.0; // here come some local variables

SP 11 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

long double n; unsigned p;

for (n = numbers, p = picks; p > 0; n--, p--) result = result * n / p ; return result; }

// pe7-6.cpp

#include

int Fill_array(double ar[], int size);

void Show_array(const double ar[], int size); void Reverse_array(double ar[], int size); const int LIMIT = 10;

int main( ) {

using namespace std; double values[LIMIT];

int entries = Fill_array(values, LIMIT); cout << \ Show_array(values, entries); cout << \ Reverse_array(values, entries); Show_array(values, entries);

cout << \ Reverse_array(values + 1, entries - 2); Show_array(values, entries);

return 0; }

int Fill_array(double ar[], int size) {

using namespace std; int n;

cout << \ for (n = 0; n < size; n++) {

cin >> ar[n]; if (!cin) break; }

return n; }

void Show_array(const double ar[], int size) {

using namespace std; int n;

for (n = 0; n < size; n++) {

cout << ar[n]; if (n % 8 == 7) cout << endl; else

cout << ' '; }

if (n % 8 != 0) cout << endl; }

void Reverse_array(double ar[], int size) {

int i, j;

SP 12 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

double temp;

for (i = 0, j = size - 1; i < j; i++, j--) {

temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } }

//pe7-9.cpp

#include

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(void) {

using namespace std;

double (*pf[3])(double,double) = {add, sub, mean}; char * op[3] = {\ double a, b;

cout << \ int i;

while (cin >> a >> b) {

// using function names

cout << calculate(a, b, add) << \ cout << calculate(a, b, mean) << \ // using pointers

for (i = 0; i < 3; i++)

cout << calculate(a, b, pf[i]) << \ << op[i] << \ }

cout << \ return 0; }

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; }

SP 13 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

Chapter 8

// pe8-1.cpp

#include

void silly(const char * s, int n = 0); int main(void) {

using namespace std;

char * p1 = \

silly(p1);

for (int i = 0; i < 3; i++) {

cout << i << \ silly(p1, i); }

cout << \ return 0; }

void silly(const char * s, int n) {

using namespace std; static int uses = 0;

int lim = ++uses; if (n == 0) lim = 1;

for (int i = 0; i < lim; i++) cout << s; }

// pe8-4.cpp

#include

#include // for strlen(), strcpy() using namespace std;

struct stringy {

char * str; // points to a string

int 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[] = \

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 once show(beany, 2); // prints member string twice testing[0] = 'D'; testing[1] = 'u';

show(testing); // prints testing string once

SP 14 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

show(testing, 3); // prints testing string thrice show(\ 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); }

// pe8-5.cpp

#include

template T max5(T ar[]) {

int n;

T max = ar[0];

for (n = 1; n < 5; n++) if (ar[n] > max) max = ar[n]; return max; }

const int LIMIT = 5; int main( ) {

using namespace std;

double ard[LIMIT] = { -3.4, 8.1, -76.4, 34.4, 2.4}; int ari[LIMIT] = {2, 3, 8, 1, 9}; double md; int mi;

md = max5(ard); mi = max5(ari);

cout << \ cout << \

return 0; }

SP 15 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

Chapter 9

PE 9-1

// pe9-golf.h - for pe9-1.cpp const int Len = 40; struct golf {

char fullname[Len]; int handicap; };

// non-interactive version

// function sets golf structure to provided name, handicap // using values passed as arguments to the function void setgolf(golf & g, const char * name, int hc);

// interactive version

// function solicits name and handicap from user // and sets the members of g to the values entered

// returns 1 if name is entered, 0 if name is empty string int setgolf(golf & g);

// function resets handicap to new value void handicap(golf & g, int hc);

// function displays contents of golf structure void showgolf(const golf & g);

// pe9-golf.cpp - for pe9-1.cpp #include #include \#include

// function solicits name and handicap from user

// returns 1 if name is entered, 0 if name is empty string int setgolf(golf & g) {

std::cout << \ std::cin.getline(g.fullname, Len); if (g.fullname[0] == '\\0')

return 0; // premature termination

std::cout << \ while (!(std::cin >> g.handicap)) {

std::cin.clear();

std::cout << \ }

while (std::cin.get() != '\\n') continue; return 1; }

// function sets golf structure to provided name, handicap void setgolf(golf & g, const char * name, int hc) {

std::strcpy(g.fullname, name); g.handicap = hc; }

// function resets handicap to new value

SP 16 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

void handicap(golf & g, int hc) {

g.handicap = hc; }

// function displays contents of golf structure void showgolf(const golf & g) {

std::cout << \ std::cout << \}

// pe9-1.cpp

#include #include \

// link with pe9-golf.cpp const int Mems = 5; int main(void) {

using namespace std; golf team[Mems];

cout << \ int i;

for (i = 0; i < Mems; i++)

if (setgolf(team[i]) == 0) break;

for (int j = 0; j < i; j++) showgolf(team[j]);

setgolf(team[0], \ showgolf(team[0]); handicap(team[0], 3); showgolf(team[0]);

return 0; }

PE 9-3

//pe9-3.cpp -- using placement new #include #include

#include struct chaff {

char dross[20]; int slag; };

// char buffer[500]; // option 1 int main() {

using std::cout; using std::endl; chaff *p1; int i;

char * buffer = new char [500]; // option 2

p1 = new (buffer) chaff[2]; // place structures in buffer std::strcpy(p1[0].dross, \ p1[0].slag = 13;

std::strcpy(p1[1].dross, \ p1[1].slag = -39;

SP 17 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

for (i = 0; i < 2; i++)

cout << p1[i].dross << \ delete [] buffer; // option 2

return 0; }

Chapter 10

PE 10-1

// pe10-1.cpp

#include #include

// class declaration class BankAccount {

private:

char name[40]; char acctnum[25]; double balance; public:

BankAccount(char * client = \ double bal = 0.0); void show(void) const; void deposit(double cash); void withdraw(double cash); };

// method definitions

BankAccount::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 << \

cout << \ cout << \}

void BankAccount::deposit(double cash) {

if (cash >= 0)

balance += cash; else

std::cout << \}

void BankAccount::withdraw(double cash) {

if (cash < 0)

std::cout << \ else if (cash <= balance) balance -=cash;

SP 18 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

else

std::cout << \}

// sample use

int main() {

BankAccount bird;

BankAccount frog(\

bird.show(); frog.show();

bird = BankAccount(\ 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 constructor Sales();

// 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 0 Sales(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 values void setSales();

// display all information in object void showSales(); }; }

#endif

SP 19 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// pe10-4a.cpp

#include #include \

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 \

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++)

SP 20 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

sales[i] =0; }

void Sales::setSales() {

double sa[QUARTERS]; int i;

for (i = 0; i < QUARTERS; i++) {

cout << \ cin >> sa[i]; }

// create temporary object, copy to invoking object *this = Sales(sa, QUARTERS); }

void Sales::showSales() {

cout << \

for (int i = 0; i < QUARTERS; i++)

cout << \ << sales[i] << endl;

cout << \ cout << \ cout << \ } }

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 class Item items[MAX]; // holds stack items int top; // index for top stack item public:

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

SP 21 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// pe10stack.cpp -- Stack member functions // for use with pe10-5.cpp

// exactly the same as stack.cpp in the text

#include \

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; } else

return false; }

bool Stack::pop(Item & item) {

if (top > 0) {

item = items[--top]; return true; } else

return false; }

// pe10-5.cpp

#include #include

#include \// link with pe10stack.cpp

void get_customer(customer & cu); int main(void) {

using namespace std;

Stack st; // create a stack of customer structures customer temp;

double payments = 0; char c;

cout << \

<< \ while (cin >> c && (c = toupper(c)) != 'Q') {

while (cin.get() != '\\n') continue;

SP 22 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

if (c != 'A' && c != 'P') {

cout << \ continue; }

switch (c) {

case 'A' : if (st.isfull())

cout << \ else {

get_customer(temp); st.push(temp); }

break;

case 'P' : if (st.isempty())

cout << \ else {

st.pop(temp);

payments += temp.payment;

cout << temp.fullname << \ cout << \ << payments << \ }

break;

default : cout << \ }

cout << \

<< \ }

cout << \ return 0; }

void get_customer(customer & cu) {

using namespace std;

cout << \ cin.getline(cu.fullname,35);

cout << \ 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 declarations

const int TSIZE = 45; // size of array to hold title struct film {

char title[TSIZE]; int rating; };

// general type definitions typedef struct film Item;

SP 23 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

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 list operations #include \

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; else

items[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 \ // array version

void showmovies(Item item); // to be used by transverse()

SP 24 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

int main(void) {

using namespace std;

simplist movies; // creates an empty list Item temp;

if (movies.isfull()) // invokes isfull() member function {

cout << \ exit(1); }

cout << \

while (cin.getline(temp.title,TSIZE) && temp.title[0] != '\\0') {

cout << \ cin >> temp.rating;

while(cin.get() != '\\n') continue;

if (movies.additem(temp) == false) {

cout << \ break; }

if (movies.isfull()) {

cout << \ break; }

cout << \ }

if (movies.isempty())

cout << \ else {

cout << \ movies.transverse(showmovies); }

cout << \ return 0; }

void showmovies(Item item) {

std::cout << \ << item.rating << std::endl; }

Chapter 11

PE 11-2

// pe11-2.h -- Vector class with <<, mode state // modified implementation #ifndef MODVECTOR_H_ #define MODVECTOR_H_ #include namespace VECTOR {

using std::ostream; class Vector {

SP 25 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

private:

double x; // horizontal value double y; // vertical value

char mode; // 'r' = rectangular, 'p' = polar // private methods for setting values void set_mag(); void set_ang();

void set_x(double, double); void set_y(double, double); public:

Vector();

Vector(double n1, double n2, char form = 'r'); void set(double n1, double n2, char form = 'r'); ~Vector();

double xval() const {return x;} // report x value double yval() const {return y;} // report y value double magval() const; // report magnitude double angval() const; // report angle

void polar_mode(); // set mode to 'p' void rect_mode(); // set mode to 'r' // operator overloading

Vector operator+(const Vector & b) const; Vector operator-(const Vector & b) const; Vector operator-() const;

Vector operator*(double n) const; // friends

friend Vector operator*(double n, const Vector & a);

friend ostream & operator<<(ostream & os, const Vector & v); };

} // end namespace VECTOR #endif

// pe11-2.cpp -- modified methods for Vector class #include

#include %using std::sqrt; using std::sin; using std::cos; using std::atan2; using std::cout;

namespace VECTOR {

const double Rad_to_deg = 57.2957795130823;

// private methods

// calculates magnitude from x and y

// set x from polar coordinate

void Vector::set_x(double mag, double ang) {

x = mag * cos(ang); }

// set y from polar coordinate

void Vector::set_y(double mag, double ang) {

y = mag * sin(ang); }

// public methods

SP 26 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

Vector::Vector() // default constructor {

x = y = 0.0; mode = 'r'; }

// construct vector from rectangular coordinates if form is r // (the default) or else from polar coordinates if form is p Vector::Vector(double n1, double n2, char form) {

mode = form;

if (form == 'r') {

x = n1; y = n2; }

else if (form == 'p') {

set_x(n1, n2 / Rad_to_deg); set_y(n1, n2 / Rad_to_deg); } else {

cout << \ cout << \ x = y = 0.0; mode = 'r'; } }

// set vector from rectangular coordinates if form is r (the // default) or else from polar coordinates if form is p void Vector:: set(double n1, double n2, char form) {

mode = form;

if (form == 'r') {

x = n1; y = n2; }

else if (form == 'p') {

set_x(n1, n2 / Rad_to_deg); set_y(n1, n2 / Rad_to_deg); } else {

cout << \ cout << \ x = y = 0.0; mode = 'r'; } }

Vector::~Vector() // destructor { }

double Vector::magval() const // report magnitude {

return sqrt(x*x +y*y); }

double Vector::angval() const // report angle

SP 27 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

{

if (x == 0.0 && y == 0.0) return 0; else

return atan2(y, x); }

void Vector::polar_mode() // set to polar mode {

mode = 'p'; }

void Vector::rect_mode() // set to rectangular mode {

mode = 'r'; }

// operator overloading // add two Vectors

Vector Vector::operator+(const Vector & b) const {

return Vector(x + b.x, y + b.y); }

// subtract Vector b from a

Vector Vector::operator-(const Vector & b) const {

return Vector(x - b.x, y - b.y); }

// reverse sign of Vector

Vector Vector::operator-() const {

return Vector(-x, -y); }

// multiple vector by n

Vector Vector::operator*(double n) const {

return Vector(n * x, n * y); }

// friend methods

// multiply n by Vector a

Vector operator*(double n, const Vector & a) {

return a * n; }

// display rectangular coordinates if mode is r, // else display polar coordinates if mode is p

ostream & operator<<(ostream & os, const Vector & v) {

if (v.mode == 'r')

os << \ else if (v.mode == 'p') {

os << \ << v.angval() * Rad_to_deg << \ } else

os << \ return os; }

SP 28 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

} // end namespace VECTOR

// pe11-2walk.cpp -- use the modified Vector class // compile with the vect.cpp file #include

#include // rand(), srand() prototypes #include // time() prototype #include \

int main() {

using namespace std; using VECTOR::Vector;

srand(time(0)); // seed random-number generator double direction; Vector step;

Vector result(0.0, 0.0); unsigned long steps = 0; double target; double dstep;

cout << \ while (cin >> target) {

cout << \ if (!(cin >> dstep)) break;

while (result.magval() < target) {

direction = rand() % 360;

step.set(dstep, direction, 'p'); result = result + step; steps++; }

cout << \ \ cout << result << endl; result.polar_mode();

cout << \

cout << \ << result.magval()/steps << endl; steps = 0;

result.set(0.0, 0.0);

cout << \ }

cout << \

return 0; }

PE 11-5

// pe11ston.h -- definition for Stonewt class (for pe 11-5) #ifndef PE11STONEWT_H_ #define PE11STONEWT_H_ #include class Stonewt {

private:

enum {Lbs_per_stn = 14}; // pounds per stone int stone; // whole stones

double pds_left; // fractional pounds

SP 29 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

double pounds; // entire weight in pounds char mode; // display mode for weight

// 's' = stone, 'f' = float, 'w' = whole pounds public:

Stonewt(double lbs); // constructor for double pounds

Stonewt(int stn, double lbs); // constructor for stone, lbs Stonewt(); // default constructor ~Stonewt();

void set_mode(char m) {mode = m; }

Stonewt operator+(const Stonewt & sw) const; Stonewt operator-(const Stonewt & sw) const; Stonewt operator*(double m) const;

friend Stonewt operator*(double m, const Stonewt & sw) { return sw * m; }

friend std::ostream & operator<<(std::ostream & os, const Stonewt & sw); };

#endif

// pe11ston.h -- definition for Stonewt class (for pe 11-5) #ifndef PE11STONEWT_H_ #define PE11STONEWT_H_ #include class Stonewt {

private:

enum {Lbs_per_stn = 14}; // pounds per stone int stone; // whole stones

double pds_left; // fractional pounds

double pounds; // entire weight in pounds char mode; // display mode for weight

// 's' = stone, 'f' = float, 'w' = whole pounds public:

Stonewt(double lbs); // constructor for double pounds

Stonewt(int stn, double lbs); // constructor for stone, lbs Stonewt(); // default constructor ~Stonewt();

void set_mode(char m) {mode = m; }

Stonewt operator+(const Stonewt & sw) const; Stonewt operator-(const Stonewt & sw) const; Stonewt operator*(double m) const;

friend Stonewt operator*(double m, const Stonewt & sw) { return sw * m; }

friend std::ostream & operator<<(std::ostream & os, const Stonewt & sw); };

#endif

// pe11-5.cpp

#include #include \

// link with pe11ston.cpp int main(void) {

using std::cout;

Stonewt fullback(245.5);

Stonewt cornerback(13, 5.2); cout << fullback; cout << cornerback;

cornerback.set_mode('w'); cout << cornerback; Stonewt lump;

lump = fullback + cornerback; cout << lump;

fullback = fullback * 1.1; cout << fullback;

SP 30 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

lump = lump - fullback; cout << lump;

lump = 1.3 * lump; lump.set_mode('s'); cout << lump;

return 0; }

PE 11-7

// pe11-7.cpp

#include

#include \int main() {

using std::cout; using std::endl; using std::cin;

complex a(3.0, 4.0); // initialize to (3,4i) complex c;

cout << \ while (cin >> c) {

cout << \

cout << \ cout << \

cout << \ cout << \ cout << \ cout << \

cout << \ }

cout << \ return 0; }

// complex0.h

#ifndef COMPLEX0_H_ #define COMPLEX0_H_ #include

class complex {

private:

double r; double i; public:

complex();

complex(double real);

complex(double real, double imag); double magnitude();

complex operator+(const complex & z) const; complex operator-(const complex & z) const; complex operator~() const;

friend complex square(const complex & z);

friend complex operator*(const complex & z, const complex & w);

friend std::ostream & operator<<(std::ostream & os, const complex & z); friend std::istream & operator>>(std::istream & is, complex & z); };

#endif

SP 31 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// complex0.cpp

#include #include

#include \

complex::complex() {

r = i = 0.0; }

complex::complex(double real) {

r = real; i = 0.0; }

complex::complex(double real, double imag) {

r = real; i = imag; }

double complex::magnitude() {

return std::sqrt(r*r + i*i); }

complex complex::operator+(const complex & z) const {

complex sum;

sum.r = r + z.r; sum.i = i + z.i; return sum; }

complex complex::operator-(const complex & z) const {

complex sum;

sum.r = r + z.r; sum.i = i + z.i; return sum; }

complex complex::operator~() const {

complex conjugate; conjugate.r = r; conjugate.i = -i; return conjugate; }

complex square (const complex & z) {

complex sq;

sq.r = z.r * z.r - z.i * z.i; sq.i = 2.0 * z.r * z.i; return sq; }

complex operator*(const complex & z, const complex & w) {

complex sq;

sq.r = w.r * z.r - w.i * z.i; sq.i = w.r * z.i + w.i * z.r; return sq; }

SP 32 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

std::ostream & operator<<(std::ostream & os, const complex & z) {

os << '(' << z.r << ',' << z.i << \ return os; }

std::istream & operator>>(std::istream & is, complex & z) {

std::cout << \ if (is >> z.r) {

std::cout << \ is >> z.i; }

return is; }

Chapter 12

PE 12-2

// pe12-2.cpp

#include //#include \

#include \int main() {

using std::cout; using std::cin;

String s1(\ String s2 = \ String s3;

cout << s2; // overloaded << operator cin >> s3; // overloaded >> operator s2 = \ cout << s2 << \ s2 = s2 + s1;

s2.stringup(); // converts string to uppercase cout << \ << \ s1 = \

// then String & operator=(const String&)

String rgb[3] = { String(s1), String(\ cout << \ String ans;

bool success = false; while (cin >> ans) {

ans.stringlow(); // converts string to lowercase for (int i = 0; i < 3; i++) {

if (ans == rgb[i]) // overloaded == operator {

cout << \ success = true; break; } }

if (success)

SP 33 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

break; else

cout << \ }

cout << \ return 0; }

// pe12strg.h

#ifndef PE12STRG_H_ #define PE12STRG_H_ #include

class String { private:

char * str; // pointer to a string int chars; // number of characters static int strings; // total number of strings public:

String();

String(const char * ps); // converts C++ string to String String(const String & s); ~String();

int numstrings(); int len();

void stringup(); void stringlow(); int has(char ch);

String & operator=(const String & s);

friend std::ostream & operator<<(std::ostream & os, const String & s); friend std::istream & operator>>(std::istream & os, String & s); friend String operator+(const String & s1, const String & s2); friend int operator==(const String & s1, const String & s2); friend int operator<(const String & s1, const String & s2); friend int operator>(const String & s1, const String & s2); };

#endif

// pe12strg.cpp

#include #include

//#include \

#include \int String::strings = 0;

String::String() {

str = NULL; chars = 0; strings++; }

String::String(const char * ps) {

chars = std::strlen(ps); str = new char [chars + 1]; std::strcpy(str, ps); strings++; }

String::String(const String & s) {

chars = s.chars;

SP 34 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

str = new char [chars + 1]; std::strcpy(str, s.str); strings++; }

String::~String() {

strings--;

delete [] str; }

int String::numstrings() {

return strings; }

int String::len() {

return chars; }

void String::stringup() {

for (int i = 0; i < chars; i++) str[i] = std::toupper(str[i]); }

void String::stringlow() {

for (int i = 0; i < chars; i++) str[i] = std::tolower(str[i]); }

String & String::operator=(const String & s) // allows chaining {

if (this == &s) // assignment to self return * this;

delete [] str; // free old contents, if any chars = s.chars;

str = new char [chars + 1]; std::strcpy(str, s.str); return * this; }

std::ostream & operator<<(std::ostream & os, const String & s) {

os << s.str; return os; }

std::istream & operator>>(std::istream & is, String & s) {

char temp[80];

is.getline(temp,80); s = temp; return is; }

String operator+(const String & s1, const String & s2) {

int len = s1.chars + s2.chars; char * ps = new char [len + 1]; std::strcpy(ps, s1.str); std::strcat(ps, s2.str);

SP 35 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

String temp(ps); return temp; }

int String::has(char ch) {

int ct = 0;

char * ps = str; while (*ps) {

if (*ps++ == ch) ++ct; }

return ct; }

int operator==(const String & s1, const String & s2) {

if (s1.chars != s2.chars) return 0;

else if (std::strcmp(s1.str, s2.str) == 0) return 1; else

return 0; }

int operator<(const String & s1, const String & s2) {

if (std::strcmp(s1.str, s2.str) < 0) return 1; else

return 0; }

int operator>(const String & s1, const String & s2) {

if (std::strcmp(s1.str, s2.str) > 0) return 1; else

return 0; }

PE 12-4

// pe12stak.h -- class definition for the stack ADT #ifndef PE12STAK_H_ #define PE12STAK_H_

typedef unsigned long Item;

class Stack {

private:

enum {MAX = 10}; // constant specific to class Item * pitems; // holds stack items

int size; // max number of elements in stack int top; // index for top stack item

Stack(const Stack & st) { } // no copying of stacks

Stack & operator=(const Stack & st) { return *this; } // no assignment public:

Stack(int n = MAX); ~Stack();

bool isempty() const; bool isfull() const;

SP 36 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// 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

// pe12stak.cpp -- Stack member functions #include \

Stack::Stack(int n) // create an empty stack {

size = n;

pitems = new Item [size]; top = 0; }

Stack::~Stack() { delete [] pitems; }

bool Stack::isempty() const {

return top == 0 ? true: false; }

bool Stack::isfull() const {

return top == size ? true: false; }

bool Stack::push(const Item & item) {

if (top < size) {

pitems[top++] = item; return true; } else

return false; }

bool Stack::pop(Item & item) {

if (top > 0) {

item = pitems[--top]; return true; } else

return false; }

// pe12-4.cpp

#include #include

#include \// link with pe12stak.cpp int main(void) {

using namespace std;

Stack st(3); // create a stack of po numbers unsigned long temp; char c;

cout << \

<< \

SP 37 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

while (cin >> c && (c = toupper(c)) != 'Q') {

while (cin.get() != '\\n') continue;

if (c != 'A' && c != 'P') {

cout << \ continue; }

switch (c) {

case 'A': if (st.isfull())

cout << \ else {

cout << \ cin >> temp; st.push(temp); }

break;

case 'P': if (st.isempty())

cout << \ else {

st.pop(temp);

cout << \ }

break;

default: cout << \ }

cout << \ << \ }

cout << \ return 0; }

PE 12-6

// pe12que.h -- interface for a queue #ifndef _QUEUE_H_ #define _QUEUE_H_

// This queue will contain Customer items class Customer {

private:

long arrive; // arrival time for customer int processtime; // processing time for customer public:

Customer() { arrive = processtime = 0; } void set(long when);

long when() const { return arrive; }

int ptime() const { return processtime; } };

typedef Customer Item;

class Queue {

private:

// class scope definitions

// Node is a nested structure definition local to this class struct Node { Item item; struct Node * next;}; enum {Q_SIZE = 10};

SP 38 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

// private class members

Node * front; // pointer to front of Queue Node * rear; // pointer to rear of Queue

int items; // current number of items in Queue const int qsize; // maximum number of items in Queue // preemptive definitions to prevent public copying Queue(const Queue & q) : qsize(0) { }

Queue & operator=(const Queue & q) { return *this;} public:

Queue(int qs = Q_SIZE); // create queue with a qs limit ~Queue();

bool isempty() const; bool isfull() const; int queuecount() const;

bool enqueue(const Item &item); // add item to end

bool dequeue(Item &item); // remove item from front };

#endif

// pe12que.cpp -- Queue and Customer methods #include \

#include // (or stdlib.h) for rand() using std::rand;

// Queue methods

Queue::Queue(int qs) : qsize(qs) {

front = rear = NULL; items = 0; }

Queue::~Queue() {

Node * temp;

while (front != NULL) // while queue is not yet empty {

temp = front; // save address of front item front = front->next;// reset pointer to next item delete temp; // delete former front } }

bool Queue::isempty() const {

return items == 0; }

bool Queue::isfull() const {

return items == qsize; }

int Queue::queuecount() const {

return items; }

// Add item to queue

bool Queue::enqueue(const Item & item) {

if (isfull())

return false;

Node * add = new Node; // create node if (add == NULL)

SP 39 of 65 September 2, 2004

Solutions for Programming Exercises in C++ Primer Plus, 5th Edition

return false; // quit if none available add->item = item; // set node pointers add->next = NULL; items++;

if (front == NULL) // if queue is empty, front = add; // place item at front else

rear->next = add; // else place at rear

rear = add; // have rear point to new node return true; }

// Place front item into item variable and remove from queue bool Queue::dequeue(Item & item) {

if (front == NULL) return false;

item = front->item; // set item to first item in queue items--;

Node * temp = front; // save location of first item front = front->next; // reset front to next item delete temp; // delete former first item if (items == 0) rear = NULL; return true; }

// customer method

// when is the time at which the customer arrives

// the arrival time is set to when and the processing // time set to a random value in the range 1 - 3 void Customer::set(long when) {

processtime = std::rand() % 3 + 1; arrive = when; }

// pe12-6.cpp -- use the Queue interface // link to pe12que.cpp

// modify Listing 12.10 by adding a second queue #include

#include // for time()

#include // for rand() and srand() #include \

const long MIN_PER_HR = 60L;

bool newcustomer(double x); // is there a new customer?

int main(void) {

using std::cin; using std::cout; using std::endl;

using std::ios_base;

// setting things up

std::srand(std::time(0)); // random initializing of rand()

cout << \ cout << \ int qs; cin >> qs;

SP 40 of 65 September 2, 2004

本文来源:https://www.bwwdw.com/article/dxt3.html

Top