c++primer plus 第12章习题

//第12章第1题
#ifndef STACK_H
#define STACK_H
#define _CRT_SECURE_NO_WARNINGS
class Cow
{
private:
	char name[20];
	char *hobby;
	double weight;
public:
	Cow();
	Cow(const char *nm, const char * ho, double wt);
	Cow(const Cow & c);
	~Cow();
	Cow & operator = (const Cow & c);
	void ShowCow()const;
};
#endif

#include"zhan.h"
#include<iostream>
//第12章第1题
Cow::Cow()
{
	weight = 0;
	name[0]= '\0';
	hobby = NULL;
}
Cow::Cow(const char *nm, const char * ho, double wt)
{
	strcpy_s(name,nm);//这里要用strcpy
	hobby = new char[strlen(ho) + 1];//这里分配
	strcpy(hobby, ho);				//这里赋值
	weight = wt;
}
Cow::Cow(const Cow & c)
{
	strcpy_s(name, c.name);
	hobby = new char[strlen(c.hobby) + 1];
	strcpy(hobby, c.hobby);
	weight = c.weight;
}
Cow::~Cow()
{
	delete[]hobby;//释放  char *
}
Cow & Cow::operator = (const Cow & c)
{
	if (this == &c)
		return *this;
	delete[]hobby;
	hobby = new char[strlen(c.hobby) + 1];
	strcpy(hobby, c.hobby);
	strcpy_s(name, c.name);
	weight = c.weight;
	return *this;
}
void Cow::ShowCow()const
{
	std::cout << "Name:" << name << "\n";
	std::cout << "Hobby:" << hobby << "\n";
	std::cout << "Weight:" << weight << "\n";
}

第12章第1题
#include<iostream>
#include"zhan.h"
#include<cstdlib>
int main()
{

	Cow c1 = { "wqf", "pingpang", 60 };
	c1.ShowCow();
	Cow c2 = { "hhj", "chifan", 50 };
	c2.ShowCow();
	Cow c3= c1;
	c3.ShowCow();
	Cow c4 ;
	c4 = c2;
	c4.ShowCow();

	system("pause");
	return 0;
}


//第12章程序第2题.
#ifndef STRING1_H
#define STRING1_H
#include<iostream>
using std::ostream;
using std::istream;

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 &s);//copy构造函数
	~String();
	int length()const{ return len; }
	//一般成员函数
	void stringlow();
	void stringup();
	int has(char);
	
	//重载操作符
	String & operator=(const String &s);
	String & operator=(const char *s);//重载=运算符
	String & operator+=(const char *s);//重载=运算符
	char & operator[](int i);
	const char& operator[](int i)const;//只能读const对象的。
	//重载友元函数
	friend String operator+(const String &s1, const String &s2);//必须声明为友元函数,重载运算符不行
	friend bool operator<(const String &st, const String &st2);
	friend bool operator>(const String &st, const String &st2);
	friend bool operator==(const String &st, const String &st2);
	friend ostream& operator<<(ostream &os, const String &st);
	friend istream& operator>>(istream &is,  String &st);//不能const ,不然怎么输入
	//设置静态函数
	static int HowMany();
};
#endif

//第12章程序第2题
#define _CRT_SECURE_NO_WARNINGS
#include"zhan.h"
#include<iostream>
#include<cstring>
#include<string.h>
#include<cctype>
using std::cin;
using std::cout;
using std::string;


int String::num_strings = 0;
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 &s)//copy构造函数
{
	num_strings++;
	len = s.len;
	str = new char[len + 1];
	std::strcpy(str, s.str);
}
String::~String()
{
	--num_strings;
	delete[]str;
}
void String::stringup()
{
	for (int i = 0; i < len; i++)
	{
		str[i] = toupper(str[i]);
	}
}
void String::stringlow()
{
	for (int i = 0; i < len; i++)
	{
		str[i] = tolower(str[i]);
	}
}
int String::has(char a)
{
	int count=0;
	for (int i = 0; i < len; i++)
	{
		if (str[i] == a)
			++count;
	}
	return count;
}

//重载操作符
String & String::operator=(const String &s)
{
	if (this == &s)//this 指针是地址
		return *this;
	delete[]str;
	len = s.len;
	str = new char[len + 1];//深copy
	std::strcpy(str, s.str);
	return *this;
}
String & String::operator+=(const char *s)//重载=运算符
{
	return *this + s;
}
String & String::operator=(const char *s)//重载=运算符 c风格
{
	delete[]str;
	len = 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//只能读const对象的。
{
	return str[i];
}
//重载友元函数
bool operator<(const String &st, const String &st2)
{
	return (std::strcmp(st.str, st2.str)<0);
}
bool operator>(const String &st, const String &st2)
{
	return (std::strcmp(st.str, st2.str)>0);
}
bool operator==(const String &st, const String &st2)
{
	return (std::strcmp(st.str, st2.str) == 0);

}
String  operator+(const String &s1, const String &s2)//必须声明为友元函数,重载运算符不行
{
	String st;
	st.len = s1.len + s2.len;
	st.str = new char[st.len + 1];
	strcpy(st.str, s1.str);
	strcat(st.str, s2.str);
	return st;
}
ostream& operator<<(ostream &os, const String &st)
{
	os << st.str;
	return os;
}
istream& operator>>(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;
}
//设置静态函数
int String::HowMany()
{
	return num_strings;
} 

//第12章第2题

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

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 int it.\n";
	s1 = "red";
	String rgb[3] = { String(s1), String("green"), String("blue") };
	cout << "Enter the name of a primay 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";
	system("pause");
	return 0;

}

//第12章第3题
#ifndef STACK_H
#define STACK_H
#define _CRT_SECURE_NO_WARNINGS
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 *str, long n = 0, double pr = 0.0);
	~Stock();
	void buy(long num, double price);
	void shell(long num, double price);
	void update(double price);
	void show()const;
	const Stock & topval(const Stock & s)const;
};


#endif

//第12章第3题
#include"zhan.h"
#include<iostream>
#include<string>
Stock::Stock()
{
	company = new char[strlen("lenovo ")];
	strcpy(company, "lenovo");
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}
Stock::Stock(const char *str, long n , double pr)
{
	company = new char[strlen(str)+1];
	strcpy(company, str);
	if (n < 0)
	{
		std::cout << "Number of shares can't be negtive;" << company << "shares set to 0.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 << "Numbers of shares purchased can't be negative." << "Transation is aborted.\n";

	}
	else
	{
		shares += num;
		share_val = price;
		set_tot();
	}
}
void Stock::shell(long num, double price)
{
	using std::cout;
	if (num < 0)
	{
		cout << "Numbers of shares sold can't be negative." << "Transaction is aborted.\n";
	}
	else if (num>shares)
	{
		cout << "You can't sell more than you have1" << "Transaction is aborted.\n";
	}
	else
	{
		shares -= num;
		share_val = price;
		set_tot();
	}
}
void Stock::update(double price)
{
	share_val = price;
	set_tot();
}
void Stock::show()const
{
	using std::cout;
	using std::ios_base;
	ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
	std::streamsize prec = cout.precision(3);
	cout << "Company:" << company << " Shares:" << shares << "\n";
	cout << " Shares price:$" << total_val << "\n";
	cout.setf(orig, ios_base::floatfield);
	cout.precision(prec);
}
const Stock & Stock::topval(const Stock & s)const
{
	if (s.total_val > total_val)
		return s;
	else
		return *this;
}
//第12章第3题
#include"zhan.h"
#include<iostream>
const int STKS = 4;
int main()
{
	Stock stocks[STKS] = { Stock("NanoSmart", 12, 20.0), Stock("Boffo Objects", 200, 2.0),
		Stock("NanoSmart", 130, 3.25), Stock("Fleep Enterprises", 60, 6.5) };
	std::cout << "Stock holdings:\n";
	int st;
	for (st = 0; st < STKS; st++)
		stocks[st].show();
	const Stock * top = &stocks[0];
	for (st = 1; st < STKS; st++)
		top = &top->topval(stocks[st]);
	std::cout << "\n Most valueable holding:\n";
	top->show();
	system("pause");
	return 0;
}


第12章第4题
#ifndef STACK_H
#define STACK_H

typedef unsigned long Item;
class Stack
{
private:
	enum{ MAX = 10 };
	Item *pitems;
	int size;
	int top;
public:
	Stack(int n = MAX)
	{
		pitems = new Item[MAX];//初始化
		size = 0;
		top = 0;
	}
	Stack(const Stack &st)//看清楚是Stack类型
	{
		pitems = new Item[st.size];
		for (int i = 0; i < st.size; i++)
		{
			pitems[i] = st.pitems[i];
			size++;
			top++;
		}
	}
	~Stack()
	{
		delete[]pitems;//必须要在这里删除
	}
	bool isempty()const
	{
		return top == 0;
	}
	bool isfull()const
	{
		return top == MAX;
	}
	bool push(const Item &item)//Item 类型
	{
		if (top < MAX)
		{
			pitems[top++] = item;
			size++;
			return true;
		}
		else
			return false;
	}
	bool pop(Item &item)
	{
		if (top > 0)
		{
			item = pitems[--top];
			--size;
			return true;
		}
		else
			return false;
	}
	Stack &operator=(const Stack &st)
	{
		delete[]pitems;//赋值时先删除旧的
		pitems = new Item[size];
		for (int i = 0; i < st.size; i++)
		{
			pitems[i] = st.pitems[i];
			size++;
			top++;
		}
	}
};

#endif
第12章第4题
#include<iostream>
#include"zhan.h"
#include<cctype>
#include<stdlib.h>
int main()
{
	using namespace std;
	Stack st;
	char ch;
	unsigned long po;
	cout << "Please enter A to add a purchase order,\n"
		<< "P to process a P0,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";
			else
				st.push(po);
			break;
		case'P':
		case'p':if (st.isempty())
			cout << "stack already empty\n";
				else
				{
					st.pop(po);
					cout << "PO #" << po << " poped\n";
				}
				break;
		}
		cout << "Please enter A to add a purchase order,\n"
			<< "P to process a P0,or Q to quit.\n";
	}
	cout << "Bye!";
	system("pause");
	return 0;
}

//第12章第5题
#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()
	{
		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)//包括copy构造函数和赋值运算符
	{
		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

//第12章第5题.
#include"zhan.h"
#include<cstdlib>


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

Queue::Queue(int qs):qsize(qs)//构造函数,这种方式让常量qsize可以在实现的时候赋值
{
	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;//把尾地址给add连在一起
	rear = add;//将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;
}

//第12章第5题
#include<iostream>
#include"zhan.h"
#include<cstdlib>
#include<ctime>

const int Min_Per_Hr = 60;

bool newcustomer(double x);

int main()
{
	using std::cin;
	using std::cout;
	using std::endl;
	using std::ios_base;

	std::srand(std::time(0));//设置时间种子
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue:";
	int qs;
	cin >> qs;
	Queue line(qs);//设置最大序列长度

	cout << "Enter the number of simulation hours: ";
	int hours;
	cin >> hours;
	long cyclelimit = Min_Per_Hr*hours;//分钟数

	cout << "Enter the average number of customers per hous: ";
	double perhour;
	cin >> perhour;
	double min_per_cust = Min_Per_Hr;//平均多少分钟来一个人

	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--;//处理业务时间-1,因为过了一分钟
		sum_line += line.queuecount();//每分钟计算一次队伍长度
	}
	if (customers > 0)
	{
		cout << "customers accepted :" << customers << endl;
		cout << "  customers served :" << served << endl;
		cout << "          turnaways:" << turnaways << endl;
		cout << "average queue size :";
		cout.precision(2);
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout << (double)sum_line / cyclelimit << endl;
		cout << " average wait time:" << (double)line_wait / served << " minutes\n";
	}
	else
		cout << "No customers!\n";
	cout << "Done!\n";
	system("pause");
	return 0;
}

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

第六题,第七题课本上有吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值