C++ Primer Plus(第六版)中文版编程练习答案

1

BankAccount.h

#pragma once
#include<iostream>
#include<string>

class BankAccount
{
private:
	string m_Name;
	string m_Account;
	double m_Money;

public:
	BankAccount();
	BankAccount(const string& name, const string& account, double money);
	void ShowAccount() const;
	void AddMoney(double money);
	void SubtractMoney(double money);
};

exercise01_BankAccount.cpp

#include<iostream>
using namespace std;
#include"BankAccount.h"

BankAccount::BankAccount()
{

}

BankAccount::BankAccount(const string& name, const string& account, double money)
{
	this->m_Name = name;
	this->m_Account = account;

	if (money < 0)
	{
		cout << "Money can't be negative!\n";
		this->m_Money = 0;
	}
	else
		this->m_Money = money;
}

void BankAccount::ShowAccount() const
{
	cout << "Name: " << this->m_Name << "\t" << "Account: " << this->m_Account << "\t"
		<< "Money: " << this->m_Money << endl;
}

void BankAccount::AddMoney(double money)
{
	if (money < 0)
		cout << "Money can't be negative!\n";
	else
		this->m_Money += money;
}

void BankAccount::SubtractMoney(double money)
{
	if (money < 0)
		cout << "Money can't be negative!\n";
	else if (money > this->m_Money)
		cout << "This account doesn't have so much money!\n";
	else
		this->m_Money -= money;
}

exercise01.cpp

#include<iostream>
using namespace std;
#include"BankAccount.h"

int main()
{
	BankAccount ba1;

	BankAccount ba2("张三", "001", 10000);
	ba2.ShowAccount();
	BankAccount ba3("李四", "002", -10000);
	ba3.ShowAccount();

	ba2.AddMoney(-10000);
	ba2.ShowAccount();
	ba2.AddMoney(10000);
	ba2.ShowAccount();

	ba2.SubtractMoney(-20000);
	ba2.ShowAccount();
	ba2.SubtractMoney(30000);
	ba2.ShowAccount();
	ba2.SubtractMoney(20000);
	ba2.ShowAccount();

	ba1 = ba2;
	ba1.ShowAccount();

	return 0;
}

2

Person.h

#pragma once
#include<iostream>
using namespace std;

class Person
{
private:
	static const int Limit = 25;
	string lname; //Person's last name
	char fname[Limit]; //Person's first name

public:
	Person() { lname = " "; fname[0] = '\0'; } //#1
	Person(const string& ln, const char* fn = "Heyyou"); //#2
	void Show() const; //firstname lastname format(格式)
	void FormalShow() const; //lastname,firstname foramt
};

exercise02_Person.cpp

#include<iostream>
#include"Person.h"
using namespace std;

//Person::Person() //#1
//{ 
//	lname = ""; 
//	fname[0] = '\0'; 
//} 

Person::Person(const string& ln, const char* fn) //#2
{
	lname = ln;
	strcpy_s(fname, fn);
}

void Person::Show() const //firstname lastname format(格式)
{
	cout << "firstname lastname format\n";
	cout << "Name: " << fname << " " << lname << endl;
}

void Person::FormalShow() const //lastname firstname foramt
{
	cout << "lastname firstname foramt\n";
	cout << "Name: " << lname << " " << fname << endl;
}

exercise02.cpp

#include<iostream>
#include"Person.h"
using namespace std;

int main()
{
	Person one;
	one.Show();
	one.FormalShow();
	cout << "--------------------------\n";

	Person two("Smythecraft");
	two.Show();
	two.FormalShow();
	cout << "--------------------------\n";

	Person three("Dimwiddy", "Sam");
	three.Show();
	three.FormalShow();

	return 0;
}

3

golf.h

#pragma once

// golf.h -- for pe9.1

class golf
{
private:
    static const int Len = 40;
    char fullname[Len];
    int handicap;

public:
    golf(); //构造函数实现交互式版本
    //有参构造,将golf结构设置为提供name、handicap
    golf(const char* name, int hc);
    void sethandicap(int hc); //将handicap设置为新的值
    void showgolf() const; //展示golf结构体的内容
};

exercise03_golf.cpp

#include<iostream>
using namespace std;
#include"golf.h"

//交互式版本,函数向用户请求name、handicap
golf::golf()
{
	char name[Len];
	cout << "Enter name:\n";
	cin.get(fullname, Len);
	cout << "Enter handicap:\n";
	cin >> handicap;

	golf g(fullname, handicap);
	*this = g;

	cin.get();
}

//有参构造,函数将golf结构设置为提供name、handicap
golf::golf(const char* name, int hc)
{
	strcpy_s(fullname, name);
	handicap = hc;
}

//将handicap设置为新的值
void golf::sethandicap(int hc)
{
	handicap = hc;
}

//1、展示golf结构体的内容
void golf::showgolf() const
{
	if (strlen(fullname) == 0) //strlen获取字符数组长度,0则为空
		cout << "name is empty!\n";
	else
		cout << "Name: " << fullname << " ,handicap: " << handicap << endl;
}

exercise01.cpp

#include<iostream>
using namespace std;
#include"golf.h"

int main()
{
	golf ann("Ann Birdfree", 24);
	//const char* name = "Ann Birdfree";
	//setgolf(ann, name, 24);
	ann.showgolf();
	cout << "--------------------------------\n";

	golf andy;
	//andy.golf();
	andy.showgolf();
	cout << "--------------------------------\n";

	ann.sethandicap(10);
	ann.showgolf();
	andy.sethandicap(20);
	andy.showgolf();
	cout << "--------------------------------\n";

	golf go[3];
	int i = 0;
	while (i < 3)//当数组填满或输入的姓名为空,循环结束
	{
		go[i].showgolf();
		i++;
		/*if(i<3)
			cout << "Next golf:\n";*/
	}

	return 0;
}

4

Sales.h

#pragma once
#include<iostream>
using namespace std;

namespace SALES
{
	class Sales
	{
	private:
		static const int QUARTERS = 4;
		double sales[QUARTERS];
		double average;
		double max;
		double min;

	public:
		//默认构造,以交互方式收集4个季度的Sales,将其存储在s的Sales中
		//并计算和存储平均值、最大值和最小值
		Sales();

		//有参构造,从数组ar中复制4个或n个中的较小者
		//并计算和存储所输入项目的平均值、最大值和最小值
		//Sales的剩余要素(如果有)设置为0
		Sales(const double ar[], int n);

		//展示 s 结构体中所有信息
		void showSales() const;
	};
}

exercise04_Sales.cpp

#include<iostream>
using namespace std;
#include"Sales.h"
#include<set>

namespace SALES
{
	//以交互方式收集4个季度的Sales,将其存储在s的Sales中
	//并计算和存储平均值、最大值和最小值
	Sales::Sales()
	{
		double maxs = -1, mins = 999999, total = 0;
		for (int i = 0; i < 4; ++i)
		{
			cout << "Enter " << i + 1 << " quarter's sales:\n";
			std::cin >> sales[i];
			maxs = maxs < sales[i] ? sales[i] : maxs;
			mins = mins > sales[i] ? sales[i] : mins;
			total += sales[i];
		}
		max = maxs;
		min = mins;
		average = total / 4;
	}

	//从数组ar中复制4个或n个中的较小者
	//并计算和存储所输入项目的平均值、最大值和最小值
	//Sales的剩余要素(如果有)设置为0
	Sales::Sales(const double ar[], int n)
	{
		double maxs = -1, mins = 999999, total = 0;
		if (n <= 4)
		{
			for (int i = 0; i < n; i++)
			{
				sales[i] = ar[i];
				maxs = maxs > sales[i] ? maxs : sales[i];
				mins = mins < sales[i] ? mins : sales[i];
				total += sales[i];
			}
			for (int i = n; i < 4; i++)
			{
				sales[i] = 0;
				maxs = maxs > sales[i] ? maxs : sales[i];
				mins = mins < sales[i] ? mins : sales[i];
			}
			max = maxs;
			min = mins;
		}
		else
		{
			//对数组 ar 进行排序 冒泡排序
			double* arr = new double[n];
			for (int i = 0; i < n; i++)
			{
				arr[i] = ar[i];
			}

			for (int i = 0; i < n - 1; i++)
			{
				for (int j = 0 ; j < n - i - 1; j++)
				{
					if (arr[j] > arr[j + 1])
					{
						double temp = arr[j];
						arr[j] = arr[j + 1];
						arr[j + 1] = temp;
					}	
				}
			}

			//然后取出前4个
			for (int i = 0; i < 4; i++)
			{
				sales[i] = arr[i];
				total += sales[i];
			}
			max = sales[3];
			min = sales[0];
		}

		average = total / 4;
		cout << "average = " << average << "\t"
			<< "max = " << max << "\t"
			<< "min = " << min << endl;
	}

	//展示 s 结构体中所有信息
	void Sales::showSales() const
	{
		for (int i = 0; i < 4; i++)
		{
			cout << "#" << i + 1 << "quarter sales:" << sales[i] << endl;
		}
		cout << "average = " << average << "\t"
			<< "max = " << max << "\t"
			<< "min = " << min << endl;
	}
}

exercise04.cpp

#include<iostream>
using namespace std;
#include"Sales.h"

int main()
{
	double arr1[3] = { 1.1, 5.5, 8.8 };
	double arr2[6] = { 1.1, 5.5, 8.8, 6.6, 3.3, 2.2 };

	SALES::Sales s1;
	s1.showSales();
	cout << "-------------------------------------\n";

	SALES::Sales s2(arr1, 3);
	s2.showSales();
	s2 = { arr2,6 };
	s2.showSales();

	return 0;
}

5

ExerciseStack.h

#pragma once
#include<iostream>
using namespace std;

struct customer
{
	char fullname[35];
	double payment;
};

typedef customer Item;

class ExerciseStack
{
private:
	enum {MAX = 10};
	Item items[MAX];
	int top;

public:
	ExerciseStack();
	bool Isempty() const;
	bool Isfull() const;
	bool push(const Item& item);
	bool pop(Item& item);
};

exercise05_ExerciseStack.cpp

#include<iostream>
#include"ExerciseStack.h"
using namespace std;

ExerciseStack::ExerciseStack()
{
	top = 0;
}

bool ExerciseStack::Isempty() const
{
	return top == 0;
}

bool ExerciseStack::Isfull() const
{
	return top == MAX;
}

bool ExerciseStack::push(const Item& item)
{
	if (top < MAX)
	{
		items[top++] = item;
		return true;
	}
	else
		return false;
}

bool ExerciseStack::pop(Item& item)
{
	if (top > 0)
	{
		item = items[--top]; //注意 -- 的位置在前边。在后错误
		return true;
	}
	else
		return false;
}

exercise05.cpp

// stacker.cpp -- testing the Stack class
#include <iostream>
#include <cctype>  // or ctype.h
#include "ExerciseStack.h"

int main()
{
    using namespace std;
    ExerciseStack est; // create an empty stack
    char ch;
    Item po;
    double total = 0;
    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': if (est.Isfull())
                           cout << "stack already full\n";
                       else
                       {
                           cout << "Enter fullname: ";
                           cin.get(po.fullname, 35);
                           cout << "Enter payment: ";
                           cin >> po.payment;
                           est.push(po);
                       }   
                       break;
             case 'P':
             case 'p': if (est.Isempty())
                           cout << "stack already empty\n";
                       else 
                       {
                           est.pop(po);
                           cout << "PO " << po.fullname << "'s payment " << po.payment << " popped\n";
                           total += po.payment;
                           cout << "Total payment: " << total << endl;
                       }
                       break;
        }
        cout << "Please enter A to add a purchase order,\n"
             << "P to process a PO, or Q to quit.\n";
    }
    cout << "Bye\n";
    return 0; 
}

6

Move.h

#pragma once
#include<iostream>
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);
};

exercise06_Move.cpp

#include<iostream>
using namespace std;
#include"Move.h"

// set x,y to a,b
Move::Move(double a, double b)
{
	x = a;
	y = b;
}

// show current x,y values
void Move::showmove() const
{
	cout << "x = " << this->x << "\t" 
		<< "y = " << this->y << endl;
}

Move Move::add(const Move& m) const
{
	return Move(x + m.x, y + m.y);
}

// reset x,y to a,b
//形参列表里写 double b = 0 出错,重定义参数
void Move::reset(double a, double b) 
{
	x = a;
	y = b;
}

exercise06.cpp

#include<iostream>
using namespace std;
#include"Move.h"

int main()
{
	Move m1;
	m1.showmove();
	cout << "---------------------\n";

	Move m2(6, 6);
	m2.showmove();
	cout << "---------------------\n";

	/*m1 = m1.add(m2);
	m1.showmove();*/
	m1.add(m2).showmove();
	m1.add(m2).add(m2).showmove();
	cout << "---------------------\n";

	m1.reset();
	m1.showmove();
	m1.reset(16, 16);
	m1.showmove();

	return 0;
}

7

Plorg.h

#pragma once
#include<iostream>
using namespace std;

class Plorg
{
private:
	static const int Len = 19;
	char p_Name[Len];
	int p_CI;

public:
	Plorg(const char* ch = "Plorga", int ci = 50);
	void changeCI(int ci);
	void showPlorg();
};

exercise07_Plorg.cpp

#include<iostream>
using namespace std;
#include"Plorg.h"

Plorg::Plorg(const char* ch, int ci)
{
	strcpy_s(p_Name, ch);
	p_CI = ci;
}

void Plorg::changeCI(int ci)
{
	p_CI = ci;
}

void Plorg::showPlorg()
{
	cout << "Plorg name: " << p_Name << "\t"
		<< "Plorg CI: " << p_CI << endl;
}

exercise07.cpp

#include<iostream>
#include"Plorg.h"
using namespace std;

int main()
{
	Plorg p1;
	p1.showPlorg();
	p1.changeCI(60);
	p1.showPlorg();
	cout << "---------------------\n";

	Plorg p2("abcd efg", 20);
	p2.showPlorg();
	p2.changeCI(60);
	p2.showPlorg();

	return 0;
}

8

list.h

#pragma once
#include<iostream>
using namespace std;

typedef int Item;

class list
{
private:
	static const int MAX = 10;
	Item items[MAX];
	int top;

public:
	list() { top = 0; }
	bool add(const Item item);
	bool isempty() const;
	bool isfull() const;
	void visit(void (*pf) (Item&));
};

exercise08_list.cpp

#include<iostream>
using namespace std;
#include"list.h"

bool list::add(const Item item)
{
	if (top < MAX)
	{
		items[top++] = item;
		return true;
	}
	else
		return false;
}

bool list::isempty() const
{
	return top == 0;
}

bool list::isfull() const
{
	return top == MAX;
}

//函数指针作为参数
void list::visit(void (*pf) (Item&))
{
	cout << "Display item: \n";
	for (int i = 0; i < top; i++)
	{
		(*pf)(items[i]);
	}
}

exercise08.cpp

#include<iostream>
using namespace std;
#include"list.h"

void Print(Item& item);

int main()
{
	list li;
	for (int i = 0; i < 16; i++)
		li.add(i);
	cout << "Is empty?(1 reperents yes, 0 reperents no)\n" << li.isempty() << endl;
	cout << "Is full?(1 reperents yes, 0 reperents no)\n" << li.isfull() << endl;
	void(*pf)(Item & item);
	pf = Print;
	li.visit(pf);

	return 0;
}

void Print(Item& item)
{
	cout << item << " ";
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值