C++ primer plus第六版第12章编程练习

1.cow.cpp

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

Cow::Cow()
{
	m_cName[0] = '\0';
	m_cHobby = NULL;
	m_dWeight = 0;
}


Cow::~Cow()
{
	delete[] m_cHobby;
	m_cHobby = NULL;
}
Cow::Cow(const char* nm, const char* ho, double wt) {
	strcpy_s(m_cName,20, nm);
	int len = strlen(ho);
	delete[] m_cHobby;
	m_cHobby = new char[len + 1];
	strcpy_s(m_cHobby,len+1, ho);
	m_cHobby[len] = '\0';
	m_dWeight = wt;
}
Cow::Cow(const Cow& c) {
	strcpy_s(m_cName,20, c.m_cName);
	int len = strlen(c.m_cHobby);
	m_cHobby = new char[len + 1];
	strcpy_s(m_cHobby,len + 1, c.m_cHobby);
	m_cHobby[len] = '\0';
	m_dWeight = c.m_dWeight;
}
Cow& Cow::operator=(const Cow& c) {
	if (this == &c)
		return *this;
	delete[] m_cHobby;
	strcpy_s(m_cName, 20, c.m_cName);
	int len = strlen(c.m_cHobby);
	m_cHobby = new char[len + 1];
	strcpy_s(m_cHobby, len + 1, c.m_cHobby);
	m_cHobby[len] = '\0';
	m_dWeight = c.m_dWeight;
	return *this;
}
void Cow::ShowCow()const {
	cout << "Cow name:" << m_cName << endl;
	cout << "Cow hobby:" << m_cHobby << endl;
	cout << "Cow weight:" << m_dWeight << endl;
}

main函数:

#include <iostream>
#include "Cow.h"

int main()
{
	Cow cow2("lily", "milk", 50);
	Cow cow3 = cow2;
	Cow cow4(cow2);
	cow2.ShowCow();
	cow3.ShowCow();
	cow4.ShowCow();
	return 0;
}

2.string.h:

#include <iostream>
using std::ostream;
using std::istream;
class String
{
public:
  String(const char* s);
  String(const String &);
  String();
  ~String();
  int length()const { return len; }
  String operator + (const String & st)const;
  void StringUp();
  void StringLow();
  int Has(const char c);
  String & operator = (const String &);
  char & operator[](int i);

  friend String operator+(const char* c, const String& st);
  friend bool operator== (const String& st, const String& st2);
  friend std::ostream & operator << (ostream & os, const String & st);
  friend std::istream & operator >> (istream & os, String & st);
private:
  char* str;
  int len;
};

string.cpp:

#include <cstring>
#include <cctype>
#include "String.h"
using std::cout;
using std::cin;

String::String()
{
  int len = 4;
  str = new char[1];
  str[0] = '\0';
}


String::~String()
{
  delete[] str;
}
String::String(const char* s) {
  len = std::strlen(s);
  str = new char[len + 1];
  strcpy_s(str,len+1, s);
}
String::String(const String & st) {
  len = st.len;
  str = new char[len + 1];
  strcpy_s(str,len+1, st.str);
}
String & String::operator = (const String & st) {
  if (this == &st)
    return *this;
  delete[] str;
  len = st.len;
  str = new char[len + 1];
  strcpy_s(str, len+1, st.str);
  return *this;
}
String operator+(const char* c, const String& st) {
	int n = st.len + strlen(c);
	char* t = new char[n + 1];
	strcpy_s(t, n + 1, c);
	strcpy_s(t + strlen(c), st.len + 1, st.str);
	t[n] = '\0';
	return String(t);
}

String String::operator + (const String & st)const {
	int n = st.len + len;
	char* t = new char[n + 1];
	strcpy_s(t, len+1, str);
	strcpy_s(t + len, st.len+1, st.str);
	t[n] = '\0';
	return String(t);
}
void String::StringUp() {
	for (int i = 0; i < len+1; ++i) {
		str[i] = toupper(str[i]);
	}	
}
void String::StringLow() {
	for (int i = 0; i < len+1; ++i) {
		str[i] = tolower(str[i]);
	}	
}
int String::Has(const char c) {
	int n = 0;
	for (int i = 0; i < len + 1; ++i) {
		if (str[i] == c)
			n++;
	}
	return n;
}

char & String::operator[](int i) { return str[i]; }
bool operator== (const String& st, const String& st2) { return (strcmp(st.str, st2.str) == 0); }
std::ostream & operator << (ostream & os, const String & st) { 
  os << st.str;
  return os;
}
std::istream & operator >> (istream & os, String & st) {
  os >> st.str;
  st.len = strlen(st.str);
  return os;
}

题目中的main函数:

#include <iostream>
#include "String.h"
using namespace std;
int main()
{
	String s1(" and I am a C++ student.");
	String s2 = "Please enter your name:";
	String s3;
	cout << s2;
	cin >> s3;
	s2 = "My name is " + s3;
	cout << s2 << ".\n";
	s2 = s2 + s1;
	s2.StringUp();
	cout << "The string\n" << s2 << "\ncontains " << s2.Has('A')
		<< "'A'characters in it.\n ";
	s1 = "red";
	String rgb[3] = { String(s1),String("green"),String("blue") };
	cout << "Enter the name of a primary color for mixing light:";
	String ans;
	bool success = false;
	while (cin>>ans)
	{
		ans.StringLow();
		for (int i = 0; i < 3; ++i) {
			if (ans == rgb[i]) {
				cout << "That's right!\n";
				success = true;
				break;
			}
		}
		if (success)
			break;
		else
			cout << "Try again!\n";
	}
	cout << "Bye!\n";
	return 0;
}

3.stock.h:

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

class Stock
{
public:
	Stock();
	Stock(const char* co, long n = 0, double pr = 0.0);
	~Stock();
	void Buy(long num, double price);
	void Sell(long num, double price);
	void Update(double price);
	void Show()const;
	const Stock& Top(const Stock& s)const;

	friend ostream& operator<<(ostream& os, const Stock& st);
private:
	char* m_c_company;
	int m_n_shares;
	double m_d_shares;
	double m_d_total;
	void set_total() { m_d_total = m_n_shares * m_d_shares; }
};

stock.cpp:

#include "Stock.h"
Stock::Stock()
{
	//m_str_company = "no names";
	m_c_company = new char[1];
	m_c_company[0] = '\0';
	m_n_shares = 0;
	m_d_shares = 0;
	m_d_total = 0;
}

Stock::~Stock()
{
	delete[] m_c_company;
	m_c_company = NULL;
}
Stock::Stock(const char* co, long n, double pr) {
	int len = strlen(co);
	m_c_company = new char[len+1];
	strcpy_s(m_c_company, len + 1, co);
	m_c_company[len] = '\0';
	if (n < 0) {
		cout << "Number of shares can't be nagative;" << m_c_company << " shares set to 0.\n";
	}
	else
		m_n_shares = n;
	m_d_shares = pr;
	set_total();
}

void Stock::Buy(long num, double price) {
	if(num<0)
		cout << "Number of shares can't be nagative;" << "Transaction is aborted.\n";
	else {
		m_n_shares += num;
		m_d_shares = price;
		set_total();
	}
}
void Stock::Sell(long num, double price) {
	if (num < 0)
		cout << "Number of shares can't be nagative;" << "Transaction is aborted.\n";
	else if (num > m_n_shares) {
		cout << "You can't sell more than you have!" << "Transaction is aborted.\n";
	}
	else {
		m_n_shares -= num;
		m_d_shares = price;
		set_total();
	}
}
void Stock::Update(double price) {
	m_d_shares = price;
	set_total();
}
const Stock& Stock::Top(const Stock& s)const {
	if (s.m_d_total > m_d_total)
		return s;
	else
		return *this;
}
ostream& operator<<(ostream& os, const Stock& st) {
	ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield);
	streamsize prec = os.precision(3);
	os << "Company: " << st.m_c_company << " Shares: " << st.m_n_shares << endl;
	os << " Share Price:$" << st.m_d_shares;
	os.precision(2);
	os << " Total Worth:$" << st.m_d_total << endl;
	os.setf(orig, ios_base::floatfield);
	os.precision(prec);
	return os;
}

4.stack.cpp

#include "Stack.h"
Stack::~Stack()
{
	delete[] m_p_items;
	m_p_items = nullptr;
}
Stack::Stack(int n ) {
	m_p_items = new Item[n];
	m_n_size = n;
	m_n_top = 0;
}
Stack::Stack(const Stack& st) {
	m_n_size = st.m_n_size;
	m_n_top = st.m_n_top;
	m_p_items = new Item[m_n_size];
	for (int i = 0; i < m_n_top; ++i) {
		m_p_items[i] = st.m_p_items[i];
	}
}
bool Stack::IsEmpty()const {	return m_n_top == 0;}
bool Stack::IsFull()const { return m_n_size == m_n_top; }
bool Stack::Push(const Item& item) {
	if (IsFull())
		return false;
	m_p_items[m_n_top] = item;
	m_n_top++;
	return true;
}
bool Stack::Pop(Item& item) {
	if (IsEmpty())
		return false;
	m_n_top--;
	item = m_p_items[m_n_top];
	return true;
}
Stack& Stack::operator=(const Stack& st) {
	m_n_size = st.m_n_size;
	m_n_top = st.m_n_top;
	m_p_items = new Item[m_n_size];
	for (int i = 0; i < m_n_top; ++i)
		m_p_items[i] = st.m_p_items[i];
	return *this;
}

main函数:

#include <iostream>
#include "Stack.h"
using namespace std;
int main()
{

	Stack stack1;
	Stack stack2(5);
	for (int i = 0; i < 5; ++i)
		stack2.Push(i);
	Stack stack3(stack2);
	if (stack2.Push(10))
		cout << "stack2 is full!\n";
	Stack stack4 = stack2;
	for (int i = 0; i < 6; ++i) {
		Item item;
		if (!stack4.Pop(item))
			cout << "stack4 is already empty,it can't pop!\n";
		else
			cout << "stack4 pop " << item << endl;
	}
	return 0;
}

题目中给出的stack.h:

#pragma once
typedef unsigned long Item;
class Stack
{
public:
	Stack(int n = MAX);
	Stack(const Stack& st);
	~Stack();
	bool IsEmpty()const;
	bool IsFull()const;
	bool Push(const Item& item);
	bool Pop(Item& item);
	Stack& operator=(const Stack& st);
private:
	enum {MAX = 10};
	Item* m_p_items;
	int m_n_size;
	int m_n_top;
};

5.题目有问题,应为“希望排队时间不超过1分钟”。按照书中,queue.h:

#pragma once
class Customer
{
public:
  Customer() { arrive = processtime = 0; }
  void set(long when) {
    processtime = std::rand() % 3 + 1;
    arrive = when;
  }
  long when()const { return arrive; }
  int ptime()const { return processtime; }
private:
  long arrive;
  int processtime;
};
typedef Customer Item;

class Queue
{
  struct Node
  {
    Item item;
    struct  Node* next;
  };
  enum { Q_SIZE = 10 };
  Queue(const Queue& q):qsize(0){}
  Queue & operator=(const Queue& q) { return *this; }
public:
  Queue(int qs = Q_SIZE);
  ~Queue();
  bool isfull();
  bool isempty();
  int queuecount()const;
  bool enqueue(const Item& item);
  bool DeleteFirstFromQueue(Item& item);

  private:
  Node * front;
  Node* rear;
  int items;
  const int qsize;
};

queue.cpp:

#include <cstdlib>
#include "Queue.h"

Queue::~Queue()
{
  Node* temp;
  while (front != NULL)
  {
    temp = front;
    front = front->next;
    delete temp;
  }
}

Queue::Queue(int qs):qsize(qs)
{
  front = rear = NULL;
  items = 0;
}
bool Queue::isfull() { return items == qsize; }
bool Queue::enqueue(const Item& item)
{
  if (isfull())
    return false;
  Node* add = new Node;
  add->item = item;
  add->next = NULL;
  items++;
  if (front == NULL)
    front = add;
  else
    rear->next = add;
  rear = add;
  return true;
}
bool Queue::DeleteFirstFromQueue(Item& item) {
  if (front == NULL)
    return false;
  item = front->item;
  items--;
  Node* temp = front;
  front = front->next;
  delete temp;
  if (items == 0)
    rear = NULL;
  return true;
}
bool Queue::isempty() { return items == 0; }
int Queue::queuecount()const { return items; }

main函数:

#include <iostream>
#include <ctime>
#include "Queue.h"
using namespace std;
const int MIN_PER_HR = 60;
bool newcustomer(double x) { return (std::rand()*x / RAND_MAX < 1); }
int main()
{
	srand(time(0));
	cout << "Case Study:Banck of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue:";
	int qs;
	cin >> qs;
	Queue line(qs);
	cout << "Set simulation hours: 100\n";
	int hours = 100;
	long cyclelimit = MIN_PER_HR * hours;
	double perhour = 15;
	double min_per_cust;
	Item temp;
	long turnaway = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait_time = 0;
	long line_wait = 0;
	double average_wait = 0;
	do {
		min_per_cust = MIN_PER_HR / perhour;
		turnaway = 0;
		customers = 0;
		served = 0;
		sum_line = 0;
		wait_time = 0;
		line_wait = 0;
		average_wait = 0;
		while (!line.isempty())
		{
			line.DeleteFirstFromQueue(temp);
		}

		for (int cycle = 0; cycle < cyclelimit; ++cycle) {
			if (newcustomer(min_per_cust)) {
				if (line.isfull())
					turnaway++;
				else {
					customers++;
					temp.set(cycle);
					line.enqueue(temp);
				}
			}
			if (wait_time <= 0 && !line.isempty()) {
				line.DeleteFirstFromQueue(temp);
				wait_time = temp.ptime();
				line_wait += cycle - temp.when();
				served++;
			}
			if (wait_time > 0)
				wait_time--;
			sum_line += line.queuecount();
		}
		if (served > 0)
			average_wait = (double)line_wait / served;
		cout << "第" << perhour - 14 << "次实验的平均等候时间为:" << average_wait << "分钟,每小时到达的客户数为:" << perhour << "个。\n";
		perhour++;
	} while (average_wait <1);
	return 0;
}

结果为:

6.main函数:

#include <iostream>
#include <ctime>
#include "Queue.h"
using namespace std;
const int MIN_PER_HR = 60;
bool newcustomer(double x) { return (std::rand()*x / RAND_MAX < 1); }
int main()
{
srand(time(0));
	cout << "Case Study:Banck of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue:";
	int qs;
	cin >> qs;
	Queue line(qs);
	Queue line2(qs);
	cout << "Set simulation hours: 100\n";
	int hours = 100;
	long cyclelimit = MIN_PER_HR * hours;
	double perhour = 30;
	double min_per_cust;
	Item temp;
	long turnaway = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait_time = 0;
	int wait_time2 = 0;
	long line_wait = 0;
	double average_wait = 0;
	do {
		min_per_cust = MIN_PER_HR / perhour;
		turnaway = 0;
		customers = 0;
		served = 0;
		sum_line = 0;
		wait_time = 0;
		wait_time2 = 0;
		line_wait = 0;
		average_wait = 0;
		while (!line.isempty())
		{
			line.DeleteFirstFromQueue(temp);
		}
		while (!line2.isempty())
		{
			line2.DeleteFirstFromQueue(temp);
		}
		for (int cycle = 0; cycle < cyclelimit; ++cycle) {
			if (newcustomer(min_per_cust)) {
				if (line.isfull()&&line2.isfull())
					turnaway++;
				else {
					customers++;
					temp.set(cycle);
					if (line.queuecount() < line2.queuecount())
						line.enqueue(temp);
					else
						line2.enqueue(temp);
				}
			}
			if (wait_time <= 0 && !line.isempty() ) {
				line.DeleteFirstFromQueue(temp);
				wait_time = temp.ptime();
				line_wait += cycle - temp.when();
				served++;
			}
			if (wait_time2 <= 0 && !line2.isempty()) {
				line2.DeleteFirstFromQueue(temp);
				wait_time2 = temp.ptime();
				line_wait += cycle - temp.when();
				served++;
			}
			if (wait_time > 0)
				wait_time--;
			if (wait_time2 > 0)
				wait_time2 -- ;
			sum_line += line.queuecount()+line2.queuecount();
		}
		if (served > 0)
			average_wait = (double)line_wait / served;
		cout << "第" << perhour - 14 << "次实验的平均等候时间为:" << average_wait << "分钟,每小时到达的客户数为:" << perhour << "个。\n";
		perhour--;
	} while (average_wait > 1);

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值