第十二章 编程练习答案
1.
//头文件
#ifndef COW_H_
#define COW_H_
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 <iostream>
#include <cstring>
#include "cow.h"
Cow::Cow()
{
name[0] = '\0';
hobby = new char[1];
hobby[0] = '\0';
weight = 0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
strcpy(name, nm);
int len;
len = std::strlen(ho);
hobby= new char[len + 1];
strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow &c)
{
std::strcpy(name, c.name);
int len;
len = std::strlen(c.hobby);
hobby = new char[len+1];
weight = c.weight;
}
Cow::~Cow()
{
delete [] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
int len;
if (this == &c)
return *this;
delete [] hobby;
weight = c.weight;
len = std::strlen(c.name);
hobby = new char[len+1];
std::strcpy(hobby, c.hobby);
std::strcpy(name, c.name);
return *this;
}
void Cow::ShowCow() const
{
std::cout << "Name: " << name << std::endl;
std::cout << "Hobby: " << hobby << std::endl;
std::cout << "Weight: " << weight << std::endl;
std::cout << std::endl;
}
//主程序文件
#include <iostream>
#include <cstring>
#include <string>
#include "cow.h"
int main()
{
using std::cout;
using std::cin;
using std::endl;
Cow a;
a.ShowCow();
Cow b("Bob", "sleep", 200.34);
b.ShowCow();
Cow c("Clummy", "run", 170.72);
c.ShowCow();
a = c;
a.ShowCow();
system("PAUSE");
return 0;
}
2.
//头文件,将书12-4适当修改
#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 &);
~String();
int length () const { return len; }
//新增函数
void stringlow();
void stringup();
int has(char c);
friend String operator+(const String & st1, const String & st2) ;
//运算符重载
String & operator=(const String & st);
String & operator=(const char * s);
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 &st1, const String &st2);
friend ostream & operator<<(ostream & os, const String &st);
friend istream & operator>>(istream & is, String &st);
static int HowMany();//静态成员函数
};
#endif
//类实现文件,将书12-5适当修改
#include <cstring>
#include <cctype>
#include "string2.h"
using std::cout;
using std::cin;
int String::num_strings = 0;//初始化为0,并且指出了类型
//初始化应该在方法文件中,不在类声明文件
int String::HowMany()//静态方法
{
return num_strings;
}
String::String(const char * s)
{
len = std::strlen(s);
str = new char[len + 1];
std::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);
}
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;
}
//新增函数的实现
void String::stringlow()
{
for (int i = 0; i < len;i++)
{
if(isupper((str[i])))
str[i]= tolower(str[i]);
}
}
void String::stringup()
{
for (int i = 0; i < len;i++)
{
if(islower((str[i])))
str[i]= toupper(str[i]);
}
}
int String::has(char c)
{
int count = 0;
for (int i = 0; i < len;i++)
{
if( str[i]== c)
count++;
}
return count;
}
String operator+(const String & st1, const String & st2)
{
String s;
s.len = st1.len + st2.len;
s.str = new char [s.len + 1];
for (int i = 0; i < st1.len; i++)
{
s.str[i] = st1.str[i];
}
for (int i = st1.len; i < s.len; i++)
{
s.str[i] = st2.str[i-st1.len];
}
s.str[s.len] = NULL;
return s;
}
/*---------加法重载的第二种方式,较为简单-------------
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;
}*/
//主程序,即书中测试代码
#include <iostream>
using namespace std;
#include "String2.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 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.
//头文件,将10-7修改
#ifndef STOCK20_H_
#define STOCK20_H-
#include <string>
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 * c0, 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 & st);
};
#endif
//类实现文件,将10-8适当修改
#include <iostream>
#include <cstring>
#include "stock30.h"
Stock::Stock()
{
company = new char[1];
company[0] = '\0';
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char * co, long n, double pr)
{
int len = 0;
len = std::strlen(co);
company = new char[len + 1];
std::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()
{
delete [] company;
}
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)
{
using std::cout;
if (num < 0)
{
cout << "Number of shares purchased can't be negative. "
<< "Transaction is aborted.\n";
}
else if (num > shares)
{
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 & st)
{
using std::ios_base;
//set format to #.###
ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield);
std::streamsize prec = os.precision(3);
os << "Company: " << st.company << " Shares: " << st.shares << '\n';
os << " Share Price: $" << st.share_val;
//set format to #.##
os.precision(2);
os << " Total Worth: $" << st.total_val << '\n';
//格式复原
os.setf(orig, ios_base::floatfield);
os.precision(prec);
return os;
}
//主程序,同10-9
#include <iostream>
#include "stock30.h"
const int STKS = 4;
int main()
{
using std::cout;
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)
};
cout << "Stock holding:\n";
int i;
for (i = 0; i < STKS; i++)
cout << stocks[i];
const Stock * top = &stocks[0];
for (i = 1; i < STKS; i++)
top = &top->topval(stocks[i]);
cout << "\nMost valuable holding:\n";
cout << *top;
return 0;
}
4.
头文件,类实现文件根据书10-10,10-11修改
//头文件
#ifndef STACK1_H_
#define STACK1_H_
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
//类实现文件
#include "stack1.h"
Stack::Stack(int n)
{
size = n;
pitems = new Item[n];
top = 0;
}
Stack::Stack(const Stack & st)
{
size = st.size;
pitems = new Item[size + 1];
for (top = 0; top < size; ++top)
pitems[top] = st.pitems[top];
}
Stack::~Stack()
{
delete [] pitems;
pitems = 0;
size = 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)
{
pitems[top++] = item;
return true;
}
else
return false;
}
bool Stack::pop(Item & item)
{
if (top > 0)
{
item = pitems[--top];
return true;
}
else
return false;
}
Stack & Stack::operator=(const Stack & st)
{
if (this == &st)
return *this;
delete [] pitems;
size = st.size;
pitems = new Item [size + 1];
for (top = 0; top < size; ++top)
pitems[top] = st.pitems[top];
return *this;
}
//主程序
#include <iostream>
#include "stack1.h"
int main()
{
using namespace std;
Stack st;
cout << "Is st empty:";
cout << st.isempty() << endl;
cout << "Is st full:";
cout << st.isfull() << endl;
Item it[10];
cout << "Push to st:";
for(int i=0;i<10;i++)
{
it[i]=i+1;
st.push(it[i]);
cout << it[i] << " ";
}
cout << "\nIs st full:";
cout << st.isfull() << endl;
Stack po;
cout << "\nAt first\nIs po empty:";
cout << po.isempty() << endl;
po = st;
cout << "\nAfter po = st\nIs po empty:";
cout << po.isempty();
cout << "\nIs po full:";
cout << po.isfull() << endl;
cout << "\nPop to st:";
for(int i=0;i<10;i++)
{
st.pop(it[i]);
cout << it[i] << " ";
}
cout << "\nIs st empty:";
cout << st.isempty() << endl;
return 0;
}
5.
代码同书上12-10,12-11,12-12
当测试数据为(10,100,18)时约为一分钟
6.
//头文件,同书12-10
#ifndef QUEUE1_H_
#define QUEUE1_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);
friend bool operator>(const Queue & item1, const Queue & item2);
};
#endif
//类实现文件
#include <cstdlib>
#include "queue1.h"
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;
}
//加入队伍,同书12-11
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 (temp == 0)
rear = NULL;
return true;
}
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
//比较人数
bool operator>(const Queue & item1, const Queue & item2)
{
return item1.items > item2.items;
}
//主程序文件,分成两个队伍计算
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue1.h"
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 maxmium size of queue: ";
int qs;
cin >> qs;
Queue line1(qs);//设有qs个人的队伍
Queue line2(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 hours: ";
double perhour;
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 wait1_time = 0;
int wait2_time = 0;
long line1_wait = 0;
long line2_wait = 0;
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust))
{
if (line1.isfull()&&line2.isfull())
turnaways++;
else if(line2 > line1 || line1.isfull())
{
customers++;
temp.set(cycle);
line1.enqueue(temp);
}
else
{
customers++;
temp.set(cycle);
line2.enqueue(temp);
}
}
if (wait1_time <= 0 && !line1.isempty())
{
line1.dequeue(temp);
wait1_time = temp.ptime();
line1_wait += cycle - temp.when();
served++;
}
if (wait2_time <= 0 && !line2.isempty())
{
line2.dequeue(temp);
wait2_time = temp.ptime();
line2_wait += cycle - temp.when();
served++;
}
if (wait1_time > 0)
wait1_time--;
sum_line += line1.queuecount();
if (wait2_time > 0)
wait2_time--;
sum_line += line2.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) (line1_wait + line2_wait) / served << " minutes\n";
}
else
cout << "No customers!\n";
cout << "Done!\n";
return 0;
}
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}
/*------------网上的第二种方法,结果接近---------------------
bool newCustomer(double x)//每隔x次,rand()/RAND_max会有一次值<1
{
return rand()*x/RAND_MAX<1;
}
int main()
{
srand(time(0));//初始化rand();
cout<<"Case Study:Bank of Heather Automatic Teller"<<endl;
cout<<"Enter maximum size of queue:";
int qs;
cin>>qs;
Queue line(qs);
Queue line2(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 hour:";//一个小时来的人数
double perhour;
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 served=0;
long sum_line=0;
int wait_time=0;
int wait_time2=0;//等待时间要+1个
long line_wait=0;
for(int cycle=0;cycle<cyclelimit;cycle++)//cycle每循环一次,代表过了一分钟
{
//line.s();
if(newCustomer(min_per_cust))
{
if(line.isfull()&&line2.isfull())//当两个队列都满了的时候才拒绝服务
turnaways++;//拒绝服务???//恩,应该就是拒绝服务的人数
else
{
customers++;//队列人数//应该是顾客人数+1而不是队列人数+1
temp.set(cycle);//cycle是到达时间
if(line.queuecount()>=line2.queuecount())
line2.enqueue(temp);
else
line.enqueue(temp);//这里的items++才是队列人数+1
//cout<<"after insert "<<line;//test
}
}
if(wait_time<=0&&!line.isempty())//队列1中有用户处理完了业务
{
line.dequeue(temp);
//cout<<"after the delete"<<line;//test
wait_time=temp.ptime();//wait_time是该客户处理业务所用时间
line_wait+=cycle-temp.when();//cycle-temp.when();是该客户一共在队列中等了多久
//一开始wait_time初始化是0,然后进入这里之后,又重新设置了使其=processtime
//line_wait是该队列一共等了多久??哦,应该是所有客户的等待时间
//line_wait是客户等待总时间
served++;//服务人数+1
}
if(wait_time2<=0&&!line2.isempty())//队列1中有用户处理完了业务
{
line2.dequeue(temp);
wait_time2=temp.ptime();//wait_time是该客户处理业务所用时间
line_wait+=cycle-temp.when();//cycle-temp.when();是该客户一共在队列中等了多久
served++;//服务人数+1
}
if(wait_time>0)//队列1正在处理业务的处理时间-1,因为过了一分钟
wait_time--;
if(wait_time2>0)//队列2正在处理业务的处理时间-1,因为过了一分钟
wait_time2--;
//wait_time=temp.ptime()这里随机设置了wait-time
sum_line+=line.queuecount()+line2.queuecount();//sum_line又是神马东东??
//sum_line是队伍总长度,每分钟计算一次队伍长度
}
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"<<endl;
}//我机器上面是18人最接近1分钟,队列长度10,时间100
else
cout<<"No coustomer!"<<endl;
cout<<"Done!"<<endl;
return 0;
}*/