C++ Primer Plus第六版 第十二章 编程练习答案

原创 2015年11月19日 16:48:16

开学到现在写了一堆代码 然而懒得写博客发2333333

AHU今年最长寒假40多天简直爽cry

话说今晚C++实验期末考试啊= =

最近一直在写各科实验的代码 还有自己论文的东西。。。这本书的题目都没怎么写= = 

//第一题
//main.cpp
#include "Cow.h"

int main()
{
	Cow a("Bob", "Fuck", 100);
	a.ShowCow();
	Cow b;
	b = a;
	b.ShowCow();

	system("PAUSE");
	return 0;
}

//Cow.h
#ifndef COW_H_
#define COW_H_

#include <iostream>
#include <cstring>

class Cow {
private:
	char name[20];
	char *hobby;
	double weight;
public:
	Cow();
	Cow(const char *nm, char *ho, double wt);
	Cow(const Cow &c);
	~Cow();
	Cow &operator=(const Cow &c);
	void ShowCow() const;
};

#endif

//Cow.cpp
#include "Cow.h"

Cow::Cow()
{
	name[0] = '\0';
	hobby = nullptr;
	weight = 0;
}

Cow::Cow(const char * nm, char * ho, double wt)
{
	strcpy_s(name, nm);
	hobby = ho;
	weight = wt;
}

Cow::Cow(const Cow & c)
{
	strcpy_s(name, c.name);
	hobby = c.hobby;
	weight = c.weight;
}

Cow::~Cow()
{
}

Cow & Cow::operator=(const Cow & c)
{
	if (this == &c)
		return *this;
	strcpy_s(name, c.name);
	hobby = c.hobby;
	weight = c.weight;
	return *this;
}

void Cow::ShowCow() const
{
	std::cout << "name: " << name << std::endl;
	std::cout << "hobby: " << hobby << std::endl;
	std::cout << "weight: " << weight << std::endl;
}



//第二题
//main.cpp
#include "string2.h"

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

//string2.h
#ifndef STRING2_H_
#define STRING2_H_

#include <iostream>

class String {
private:
	char *str;
	int len;
	static int num_strings;
	static const int CINLIM = 80;
public:
	String(const char *s);
	String();
	String(const String &);
	~String();
	int length() const { return len; }
	String &operator=(const String &);
	String &operator=(const char *);
	char &operator[](int i);
	const char &operator[](int i) const;
	friend bool operator<(const String &st1, const String &st2);
	friend bool operator>(const String &st1, const String &st2);
	friend bool operator==(const String &st, const String &st2);
	friend std::ostream &operator<<(std::ostream &os, const String &st);
	friend std::istream &operator>>(std::istream &is, String &st);
	static int HowMany();

	friend String operator+(const String &st1, const String &st2);
	void Stringlow();
	void Stringup();
	int has(char c);
};

#endif

//string2.cpp
#include "string2.h"

#include <cstring>

int String::num_strings = 0;

int String::HowMany()
{
	return num_strings;
}

void String::Stringlow()
{
	const int num = 'a' - 'A';
	for (int i = 0; i < len; ++i)
	{
		if (str[i] >= 'A' && str[i] <= 'Z')
			str[i] += num;
	}
}

void String::Stringup()
{
	const int num = 'a' - 'A';
	for (int i = 0; i < len; ++i)
	{
		if (str[i] >= 'a' && str[i] <= 'z')
			str[i] -= num;
	}
}

int String::has(char c)
{
	int num = 0;
	for (int i = 0; i < len; ++i)
		if (c == str[i])
			++num;
	return num;
}

String::String(const char *s)
{
	len = std::strlen(s);
	str = new char[len + 1];
	strcpy(str, s);
	num_strings++;
}

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

String::String(const String &st)
{
	num_strings++;
	len = st.len;
	str = new char[len + 1];
	std::strcpy(str, st.str);
}

String::~String()
{
	--num_strings;
	delete[] str;
}

String &String::operator=(const String &st)
{
	if (this == &st)
		return *this;
	delete[] str;
	len = st.len;
	str = new char[len + 1];
	std::strcpy(str, st.str);
	return *this;
}

String &String::operator=(const char *s)
{
	delete[] str;
	len = std::strlen(s);
	str = new char[len + 1];
	std::strcpy(str, s);
	return *this;
}

char &String::operator[](int i)
{
	return str[i];
}

const char &String::operator[](int i) const
{
	return str[i];
}

bool operator<(const String &st1, const String &st2)
{
	return (std::strcmp(st1.str, st2.str) < 0);
}

bool operator>(const String &st1, const String &st2)
{
	return st2 < st1;
}

bool operator==(const String &st1, const String &st2)
{
	return (std::strcmp(st1.str, st2.str) == 0);
}

std::ostream &operator<<(std::ostream &os, const String &st)
{
	os << st.str;
	return os;
}

std::istream &operator>>(std::istream &is, String &st)
{
	char temp[String::CINLIM];
	is.get(temp, String::CINLIM);
	if (is)
		st = temp;
	while (is && is.get() != '\n')
		continue;
	return is;
}

String operator+(const String &st1, const String &st2)
{
	String s;
	s.len = st1.len + st2.len;
	s.str = new char[s.len + 1];
	strcpy(s.str, st1.str);
	strcat(s.str, st2.str);
	return s;
}


//第三题
//main.cpp
#include "stock20.h"

const int STKS = 4;

int main()
{
	Stock stocks[STKS] = {
		Stock("NanoSmart", 12, 20.0),
		Stock("Boffo Objects", 200, 2.0),
		Stock("Monolithic, Obelisks", 130, 3.25),
		Stock("Fleep Enterprises", 60, 6.5)
	};
	std::cout << "Stock holdings:\n";
	int st;
	for (st = 0; st < STKS; ++st)
		std::cout << stocks[st];
	const Stock *top = &stocks[0];
	for (st = 1; st < STKS; ++st)
		top = &top->topval(stocks[st]);
	std::cout << "\nMost valuable holding: \n";
	std::cout << (*top);
	system("PAUSE");
	return 0;
}

//stock20.h
#ifndef STOCK20_H_
#define STOCK20_H_

#include <iostream>

class Stock {
private:
	char *company;
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }
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);
	const Stock &topval(const Stock &s) const;
	friend std::ostream &operator<<(std::ostream &os, const Stock &s);
};

#endif

//stock20.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "stock20.h"

Stock::Stock()
{
	company = "no name";
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

Stock::Stock(const char * co, long n, double pr)
{
	int len = strlen(co);
	company = new char[len + 1];
	strcpy(company, co);

	if (n < 0)
	{
		std::cout << "Number of shares can't be negative; "
			<< company << " shares set to 0.\n";
		shares = 0;
	}
	else
		shares = n;
	share_val = pr;
	set_tot();
}

Stock::~Stock()
{
}

void Stock::buy(long num, double price)
{
	if (num < 0)
	{
		std::cout << "Number of shares purchased can't be negative. "
			<< "Transaction is aborted. \n";
	}
	else
	{
		shares += num;
		share_val = price;
		set_tot();
	}
}

void Stock::sell(long num, double price)
{
	if (num < 0)
	{
		std::cout << "Number of shares sold can't be negative. "
			<< "Transaction is aborted.\n";
	}
	else if (num > shares)
	{
		std::cout << "You can't sell more than you have! "
			<< "Transaction is aborted.\n";
	}
	else
	{
		shares -= num;
		share_val = price;
		set_tot();
	}
}

void Stock::update(double price)
{
	share_val = price;
	set_tot();
}

const Stock & Stock::topval(const Stock & s) const
{
	if (s.total_val > total_val)
		return s;
	else
		return *this;
}


std::ostream &operator<<(std::ostream &os, const Stock &s)
{
	std::ios_base::fmtflags orig = os.setf(std::ios_base::fixed, std::ios_base::floatfield);
	std::streamsize prec = os.precision(3);

	os << "Company: " << s.company << "  Shares: " << s.shares << '\n';
	os << "  Share Price: $" << s.share_val;
	os.precision(2);
	os << "  Total Worth: $" << s.total_val << '\n';

	os.setf(orig, std::ios_base::floatfield);
	os.precision(prec);
	return os;
}


//第四题
//main.cpp
#include "stack.h"

int main()
{
	Stack s(10);

	std::cout << s.isempty() << std::endl;
	s.push(100);
	std::cout << s.isempty() << std::endl;

	return 0;
}

//stack.h
#ifndef STACK_H_
#define STACK_H_

#include <iostream>

typedef unsigned long Item;

class Stack
{
private:
	enum { MAX = 10};
	Item *pitems;
	int size;
	int top;
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);
};

#endif

//stack.cpp
#include "stack.h"

Stack::Stack(int n)
{
	pitems = new Item[n];
	size = n;
	top = 0;
}

Stack::Stack(const Stack & st)
{
	pitems = new Item[st.size];
	size = st.size;
	for (top = 0; top < size; ++top)
		pitems[top] = st.pitems[top];
}

Stack::~Stack()
{
	delete[] pitems;
	pitems = NULL;
	size = top = 0;
}

bool Stack::isempty() const
{
	return top ? false : true;
}

bool Stack::isfull() const
{
	return top == size ? true : false;
}

bool Stack::push(const Item & item)
{
	if (isfull())
		return false;
	pitems[top++] = item;
	return true;
}

bool Stack::pop(Item & item)
{
	if (isempty())
		return false;
	--top;
	return true;
}

Stack & Stack::operator=(const Stack & st)
{
	if (this == &st)
		return *this;
	pitems = new Item[st.size];
	size = st.size;
	for (top = 0; top < size; ++top)
		pitems[top] = st.pitems[top];
	return *this;
}


//第五题
//这题直接用书上代码 多输入几个数据测试一下就可以了。。。我做大概是队列10个人 17个客户的时候为1分钟
//bank.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
	std::srand(std::time(0));
	std::cout << "Case Study: Bank of Heather Automatic Teller\n";
	std::cout << "Enter maximum size of queue: ";
	int qs;
	std::cin >> qs;
	Queue line(qs);

	std::cout << "Enter the number of simulation hours: ";
	int hours;
	std::cin >> hours;
	long cyclelimit = MIN_PER_HR * hours;

	std::cout << "Enter the average number of customers per hour: ";
	double perhour;
	std::cin >> perhour;
	double min_per_cust;
	min_per_cust = MIN_PER_HR / perhour;

	Item temp;
	long turnaways = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait_time = 0;
	long line_wait = 0;

	for (int cycle = 0; cycle < cyclelimit; ++cycle)
	{
		if (newcustomer(min_per_cust))
		{
			if (line.isfull())
				++turnaways;
			else
			{
				++customers;
				temp.set(cycle);
				line.enqueue(temp);
			}
		}
		if (wait_time <= 0 && !line.isempty())
		{
			line.dequeue(temp);
			wait_time = temp.ptime();
			line_wait += cycle - temp.when();
			++served;
		}
		if (wait_time > 0)
			--wait_time;
		sum_line += line.queuecount();
	}

	if (customers > 0)
	{
		std::cout << "customers accepted: " << customers << std::endl;
		std::cout << " customers serverd: " << served << std::endl;
		std::cout << "     turnaways: " << turnaways << std::endl;
		std::cout << "average queue size: ";
		std::cout.precision(2);
		std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
		std::cout << (double)sum_line / cyclelimit << std::endl;
		std::cout << " average wait time: " << (double)line_wait / served << " minutes  \n";
	}
	else
		std::cout << "No customers!\n";
	std::cout << "Done!\n";

	return 0;
}

bool newcustomer(double x)
{
	return (std::rand() * x / RAND_MAX < 1);
}

//queue.h
#ifndef QUEUE_H_
#define QUEUE_H_

class Customer
{
private:
	long arrive;
	int processtime;
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:
	struct Node { Item item; struct Node *next; };
	enum { Q_SIZE = 10 };
	Node *front;
	Node *rear;
	int items;
	const int qsize;
	Queue(const Queue &q) : qsize(0) {}
	Queue &operator=(const Queue &q) { return *this; }
public:
	Queue(int qs = Q_SIZE);
	~Queue();
	bool isempty() const;
	bool isfull() const;
	int queuecount() const;
	bool enqueue(const Item &item);
	bool dequeue(Item &item);
};

#endif

//queue.cpp
#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs) : qsize(qs)
{
	front = rear = NULL;
	items = 0;
}

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

bool Queue::isempty() const
{
	return items == 0;
}

bool Queue::isfull() const
{
	return items == qsize;
}

int Queue::queuecount() const
{
	return items;
}

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::dequeue(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;
}

void Customer::set(long when)
{
	processtime = std::rand() % 3 + 1;
	arrive = when;
}


//第六题
//这题我两个队列时间上有差距 不知道是题目就是这样还是我写的有问题。。。队列长度取10 100小时 55个客户的时候 第一队列的0.59 第二队列1 = =
//bank.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
	std::srand(std::time(0));
	std::cout << "Case Study: Bank of Heather Automatic Teller\n";
	std::cout << "Enter maximum size of queue: ";
	int qs;
	std::cin >> qs;
	Queue line1(qs);
	Queue line2(qs);

	std::cout << "Enter the number of simulation hours: ";
	int hours;
	std::cin >> hours;
	long cyclelimit = MIN_PER_HR * hours;

	std::cout << "Enter the average number of customers per hour: ";
	double perhour;
	std::cin >> perhour;
	double min_per_cust;
	min_per_cust = MIN_PER_HR / perhour;

	Item temp1, temp2;
	long turnaways = 0;
	long customers = 0;
	long served = 0;
	long sum_line1 = 0;
	long sum_line2 = 0;
	int wait_time1 = 0;
	int wait_time2 = 0;
	long line_wait1 = 0;
	long line_wait2 = 0;

	for (int cycle = 0; cycle < cyclelimit; ++cycle)
	{
		if (newcustomer(min_per_cust))
		{
			if (line1.isfull() && line2.isfull())
				++turnaways;
			else
			{
				++customers;
				temp1.set(cycle);
				if (line1.queuecount() < line2.queuecount())
					line1.enqueue(temp1);
				else
					line2.enqueue(temp1);
			}
		}
		if (wait_time1 <= 0 && !line1.isempty())
		{
			line1.dequeue(temp1);
			wait_time1 = temp1.ptime();
			line_wait1 += cycle - temp1.when();
			++served;
		}
		if (wait_time2 <= 0 && !line2.isempty())
		{
			line2.dequeue(temp2);
			wait_time2 = temp2.ptime();
			line_wait2 += cycle - temp2.when();
			++served;
		}
		if (wait_time1 > 0)
			--wait_time1;
		if (wait_time2 > 0)
			--wait_time2;
		sum_line1 += line1.queuecount();
		sum_line2 += line2.queuecount();
	}

	if (customers > 0)
	{
		std::cout << "customers accepted: " << customers << std::endl;
		std::cout << " customers serverd: " << served << std::endl;
		std::cout << "     turnaways: " << turnaways << std::endl;
		std::cout << "average queue size: ";
		std::cout.precision(2);
		std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
		std::cout << (double)sum_line1 / cyclelimit << std::endl;
		std::cout << (double)sum_line2 / cyclelimit << std::endl;
		std::cout << " average wait time: " << (double)line_wait1 / served << " minutes  \n";
		std::cout << " average wait time: " << (double)line_wait2 / served << " minutes  \n";
	}
	else
		std::cout << "No customers!\n";
	std::cout << "Done!\n";

	return 0;
}

bool newcustomer(double x)
{
	return (std::rand() * x / RAND_MAX < 1);
}

//queue.h
#ifndef QUEUE_H_
#define QUEUE_H_

class Customer
{
private:
	long arrive;
	int processtime;
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:
	struct Node { Item item; struct Node *next; };
	enum { Q_SIZE = 10 };
	Node *front;
	Node *rear;
	int items;
	const int qsize;
	Queue(const Queue &q) : qsize(0) {}
	Queue &operator=(const Queue &q) { return *this; }
public:
	Queue(int qs = Q_SIZE);
	~Queue();
	bool isempty() const;
	bool isfull() const;
	int queuecount() const;
	bool enqueue(const Item &item);
	bool dequeue(Item &item);
};

#endif

//queue.cpp
#include "queue.h"
#include <cstdlib>

Queue::Queue(int qs) : qsize(qs)
{
	front = rear = NULL;
	items = 0;
}

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

bool Queue::isempty() const
{
	return items == 0;
}

bool Queue::isfull() const
{
	return items == qsize;
}

int Queue::queuecount() const
{
	return items;
}

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::dequeue(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;
}

void Customer::set(long when)
{
	processtime = std::rand() % 3 + 1;
	arrive = when;
}


相关文章推荐

c++ primer plus(第6版)中文版 第十二章编程练习答案

第十二章编程练习答案

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

c++ Primer Plus(第六版)第十二章习题,写代码之路

c++ Primer Plus(习题12.1) //12.1头文件 #pragma once #ifndef COW_H #define COW_H #include #include class ...
  • Robot_x
  • Robot_x
  • 2017年01月20日 13:01
  • 325

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

《C++ Primer Plus(第六版)》(24)(第十二章 类和动态内存分配 编程题和答案)

1.对于下面的类声明: class Cow { private: char name[20]; char * hobby; do...

(一二六)第十一章编程练习

这是我创建的专辑,所有学习笔记都以word格式上传,放在里面,相对更美观和直接。欢迎下载浏览。 http://download.csdn.net/album/detail/2971 ...

c++primer第五版第十二章练习

12.1 b1=b2,所以都有4个元素 b2离开作用域后被摧毁,但计数器不为0,内存不用释放 12.2 #ifndef HEAD_H_ #define HEAD_H_ #include #inc...

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

第四章编程练习答案 4.1接收姓名,成绩等级和年龄,输出时成绩等级下调

C++primer plus第六版课后编程题答案12.6

myQueue,cpp不变 main126.cpp #include #include "myQueue.cpp" #include #include using namespace std...

c++ primer plus(第6版)中文版 第十二章编程练习答案

第十二章编程练习答案
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:C++ Primer Plus第六版 第十二章 编程练习答案
举报原因:
原因补充:

(最多只允许输入30个字)