《C++ Primer Plus》(第6版)第12章编程练习
《C++ Primer Plus》(第6版)第12章编程练习
- 《C++ Primer Plus》(第6版)第12章编程练习
- 1. Cow类
- 2. String类
- 3. Stock类
- 4. Stack类
- 5. 排队时间不超过1分钟
- 6. 再开设一台ATM,重新求解第五题
《C++ Primer Plus》(第6版)第12章编程练习
1. Cow类
对于下面的类声明:
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;
};
给这个类提供实现,并编写一个使用所有成员函数的小程序。
代码:
cow.h:
#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
cow.cpp:
#include "cow.h"
#include <iostream>
#include <cstring>
using std::strcpy;
using std::strlen;
Cow::Cow()
{
name[0] = '\0';
hobby = new char[1];
hobby[0] = '\0';
weight = 0.0;
}
Cow::Cow(const char *nm, const char *ho, double wt)
{
strcpy(name, nm);
hobby = new char[strlen(ho) + 1];
strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow &c)
{
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow &Cow::operator=(const Cow &c)
{
if (this == &c)
return *this;
delete[] hobby;
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
using std::cout;
using std::endl;
cout << "Name: " << name << endl;
cout << "Hobby: " << hobby << endl;
cout << "Weight: " << weight << endl;
}
main.cpp:
#include "cow.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Cow c1;
cout << "c1: " << endl;
c1.ShowCow();
Cow c2("Cow2", "study", 100.23);
cout << "c2: " << endl;
c2.ShowCow();
Cow c3("Cow3", "play game", 150.80);
cout << "c3: " << endl;
c3.ShowCow();
Cow c4(c2);
cout << "c4: " << endl;
c4.ShowCow();
c1 = c3;
cout << "c1 = c3: " << endl;
c3.ShowCow();
c1.ShowCow();
system("pause");
return 0;
}
运行结果:
2. String类
通过完成下面的工作来改进String类声明(即将String1.h升级为String2.h)。
a. 对+运算符进行重载,使之可将两个字符串合并成1个。
b. 提供一个Stringlow()成员函数,将字符串中所有的字母字符转换为小写(别忘了cctype系列字符函数)。
c. 提供String()成员函数,将字符串中所有字母字符转换成大写。
d. 提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数。
使用下面的程序来测试您的工作:
#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";
system("pause");
return 0;
}
输出应与下面相似:
Please enter your name: Fretta Farbo
My name is Fretta Farbo.
The string
MY NAME IS FRETTA FARBO AND I AM A C++ STUDENT.
contains 6 'A' characters in it.
Enter the name of a primary color for mixing light: yellow
Try again!
BLUE
That's right!
Bye
代码:
string2.h:
#ifndef STRING2_H_
#define STRING2_H_
#include <iostream>
using std::istream;
using std::ostream;
class String
{
private:
/* data */
char *str;
int len;
static int num_strings;
enum
{
CINLIM = 80
};
public:
String(const char *s);
String();
String(const String &s);
~String();
int length() const { return len; }
String &operator=(const String &s);
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 &s);
friend istream &operator>>(istream &is, String &s);
static int HowMany();
// 新增函数
// a.对+运算符进行重载,使之可将两个字符串合并成1个
String operator+(const String &s) const;
String operator+(const char *s) const;
friend String operator+(const char *s1, const String &s2);
// b.提供一个String()成员函数,将字符串中所有的字母字符转换为小写
void stringlow();
// c.提供String()成员函数,将字符串中所有字母字符转换成大写
void stringup();
// d.提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数
int has(char ch);
};
#endif
string2.cpp:
#include "string2.h"
#include <cstring>
using std::strcmp;
using std::strcpy;
using std::strlen;
int String::num_strings = 0;
String::String(const char *s)
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
num_strings++;
}
String::String()
{
len = 0;
str = new char[len + 1];
strcpy(str, "\0");
num_strings++;
}
String::String(const String &s)
{
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
num_strings++;
}
String::~String()
{
num_strings--;
delete[] str;
}
String &String::operator=(const String &s)
{
if (this == &s)
return *this;
delete[] str;
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
return *this;
}
String &String::operator=(const char *s)
{
delete[] str;
len = strlen(s);
str = new char[len + 1];
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 (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 (strcmp(st1.str, st2.str) == 0);
}
ostream &operator<<(ostream &os, const String &s)
{
os << s.str;
return os;
}
istream &operator>>(istream &is, String &s)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
s = temp;
while (is && is.get() != '\n')
continue;
return is;
}
// 新增函数
// a.对+运算符进行重载,使之可将两个字符串合并成1个
String String::operator+(const String &s) const
{
char *temp = new char[len + s.len + 1];
strcpy(temp, str);
strcpy(temp + len, s.str);
return String(temp);
}
String String::operator+(const char *s) const
{
char *temp = new char[len + strlen(s) + 1];
strcpy(temp, str);
strcpy(temp + len, s);
return String(temp);
}
String operator+(const char *s1, const String &s2)
{
char *temp = new char[strlen(s1) + s2.len + 1];
strcpy(temp, s1);
strcpy(temp + strlen(s1), s2.str);
return String(temp);
}
// b.提供一个String()成员函数,将字符串中所有的字母字符转换为小写
void String::stringlow()
{
for (int i = 0; i < len; i++)
{
str[i] = tolower(str[i]);
}
}
// c.提供String()成员函数,将字符串中所有字母字符转换成大写
void String::stringup()
{
for (int i = 0; i < len; i++)
{
str[i] = toupper(str[i]);
}
}
// d.提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数
int String::has(char ch)
{
int count = 0;
for (int i = 0; i < len; i++)
if (str[i] == ch)
count++;
return count;
}
pe12_2.cpp:
#include "string2.h"
#include <iostream>
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";
system("pause");
return 0;
}
运行结果:
3. Stock类
新编写程序清单10.7和程序清单10.8描述的Stock类,使之使用动态内存分配的内存,而不是string类对象来存储股票名称。另外,使用重载的operator<<()定义代替show()成员函数。再使用程序清单10.9测试新的定义程序。
代码:
stock.h:
#ifndef STOCK_H_
#define STOCK_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);
friend std::ostream &operator<<(std::ostream &os, const Stock &st);
const Stock &topval(const Stock &s) const;
};
#endif
stock.cpp:
#include "stock.h"
#include <iostream>
#include <cstring>
using std::cout;
using std::ios_base;
using std::strcpy;
using std::strlen;
Stock::Stock()
{
company = new char[strlen("no name") + 1];
strcpy(company, "no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char *co, long n, double pr)
{
company = new char[strlen(co) + 1];
strcpy(company, co);
if (n < 0)
{
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)
{
if (num < 0)
{
cout << "Number of shares sold 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();
}
std::ostream &operator<<(std::ostream &os, const Stock &st)
{
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';
// restore original format
os.setf(orig, ios_base::floatfield);
os.precision(prec);
return os;
}
const Stock &Stock::topval(const Stock &s) const
{
if (s.total_val > total_val)
return s;
else
return *this;
}
usestock.cpp:
#include "stock.h"
#include <iostream>
const int STKS = 4;
int main()
{
{
// create an array of initialized objects
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];
// set pointer to first element
const Stock *top = &stocks[0];
for (st = 1; st < STKS; st++)
top = &top->topval(stocks[st]);
// now top points to the most valuable holding
std::cout << "\nMost valuable holding:\n";
std::cout << *top;
}
system("pause");
return 0;
}
运行结果:
4. Stack类
请看下面程序清单10.10定义的Stack类的变量:
typedef unsigned long Item;
class Stack
{
private:
enum
{
MAX = 10
}; // constant specific to class
Item *pitems; // holds stack items
int size;
int top; // index for top stack item
public:
Stack(int n = MAX);
Stack(const Stack &st);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item &item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item &item); // pop top into item
Stack &operator=(const Stack &st);
};
正如私有成员表明的,这个类使用动态内存分配的数组来保存栈项。请重新编写方法,以适应这种新的表示法,并编写一个程序来演示所有的方法,包括复制构造函数和赋值运算符。
代码:
stack.h:
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack
{
private:
enum
{
MAX = 10
}; // constant specific to class
Item *pitems; // holds stack items
int size;
int top; // index for top stack item
public:
Stack(int n = MAX);
Stack(const Stack &st);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item &item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item &item); // pop top into item
Stack &operator=(const Stack &st);
};
#endif
stack.cpp:
#include "stack.h"
#include <iostream>
Stack::Stack(int n)
{
pitems = new Item[n];
size = n;
top = 0;
}
Stack::Stack(const Stack &st)
{
pitems = new Item[st.size];
for (int i = 0; i < st.size; i++)
pitems[i] = st.pitems[i];
size = st.size;
top = st.top;
}
Stack::~Stack()
{
delete[] pitems;
}
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;
pitems = new Item[st.size];
for (int i = 0; i < size; i++)
pitems[i] = st.pitems[i];
size = st.size;
top = st.top;
return *this;
}
main.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
const bool YES = true;
int main()
{
Stack st1;
Stack st2;
Item num[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++)
{
st2.push(num[i]);
cout << num[i] << " pushed into Stack st2.\n";
}
cout << endl;
cout << "Is Stack st2 empty? " << st2.isempty() << endl;
cout << "Is Stack st2 full? " << st2.isfull() << endl;
st1 = st2;
cout << "st1 = st2: " << endl;
cout << "Is Stack st1 empty? " << st1.isempty() << endl;
cout << "Is Stack st1 full? " << st1.isfull() << endl;
Stack st3(st2);
cout << "Use st2 to build st3: " << endl;
cout << "Is Stack st3 empty? " << st3.isempty() << endl;
cout << "Is Stack st3 full? " << st3.isfull() << endl;
for (int i = 0; i < 10; i++)
{
st2.pop(num[i]);
cout << num[i] << " poped from Stack st2.\n";
}
cout << "Stack st2 finish poping totally." << endl;
cout << "Is Stack st2 empty: " << st2.isempty() << endl;
cout << "Is Stack st2 full: " << st2.isfull() << endl;
for (int i = 0; i < 6; i++)
{
st3.pop(num[i]);
cout << num[i] << " poped from Stack st3.\n";
}
cout << "Stack st3 finish poping partly." << endl;
cout << "Is Stack st3 empty: " << st3.isempty() << endl;
cout << "Is Stack st3 full: " << st3.isfull() << endl;
system("pause");
return 0;
}
运行结果:
5. 排队时间不超过1分钟
Heather银行进行的研究表明,ATM客户不希望排队时间不超过1分钟。使用程序清单12.10中的模拟,找出要使平均等候时间为1分钟,每小时到达的客户数应为多少(试验时间不短于100小时)?
代码:
queue.h:
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:
long arrive; // arrival time for customer
int processtime; // processing time for customer
public:
Customer() : arrive(0), processtime(0) {}
void set(long when);
long when() const { return arrive; }
int ptime() const { return processtime; }
};
typedef Customer Item;
class Queue
{
private:
// class scope definitions
// Node is a nested structure definition local to this class
struct Node
{
Item item;
struct Node *next;
};
enum
{
Q_SIZE = 10
};
// private class members
Node *front; // pointer to front of Queue
Node *rear; // pointer to rear of Queue
int items; // current number of items in Queue
const int qsize; // maximum number of items in Queue
// preemptive definitions to prevent public copying
Queue(const Queue &q) : qsize(0) {}
Queue &operator=(const Queue &q) { return *this; }
public:
Queue(int qs = Q_SIZE); // create queue with a qs limit
~Queue();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const Item &item); // add item to end
bool dequeue(Item &item); // remove item from front
};
#endif
queue.cpp:
#include "queue.h"
#include <cstdlib> // (or stdlib.h) for rand()
// Queue methods
Queue::Queue(int qs) : qsize(qs)
{
front = rear = NULL; // or nullptr
items = 0;
}
Queue::~Queue()
{
Node *temp;
while (front != NULL) // while queue is not yet empty
{
temp = front; // save address of front item
front = front->next; // reset pointer to next item
delete temp; // delete former front
}
}
bool Queue::isempty() const
{
return items == 0;
}
bool Queue::isfull() const
{
return items == qsize;
}
int Queue::queuecount() const
{
return items;
}
// Add item to queue
bool Queue::enqueue(const Item &item)
{
if (isfull())
return false;
Node *add = new Node; // create node
// on failure, new throws std::bad_alloc exception
add->item = item; // set node pointers
add->next = NULL; // or nullptr;
items++;
if (front == NULL) // if queue is empty,
front = add; // place item at front
else
rear->next = add; // else place at rear
rear = add; // have rear point to new node
return true;
}
// Place front item into item variable and remove from queue
bool Queue::dequeue(Item &item)
{
if (front == NULL)
return false;
item = front->item; // set item to first item in queue
items--;
Node *temp = front; // save location of first item
front = front->next; // reset front to next item
delete temp; // delete former first item
if (items == 0)
rear = NULL;
return true;
}
// customer method
// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
main.cpp:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include "queue.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x); // is there a new customer?
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs;
Queue line(qs); // line queue holds up to qs people
cout << "The simulation hours: ";
int hours = 100;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "The average number of customers per hour: ";
double perhour = 1;
double min_per_cust; // average time between arrivals
Item temp; // new customer data
long turnaways = 0; // turned away by full queue
long customers = 0; // joined the queue
long served = 0; // served during the simulation
long sum_line = 0; // cumulative line length
int wait_time = 0; // time until autoteller is free
long line_wait = 0; // cumulative time in line
double avetime = 0;
// running the simulation
while (avetime <= 1)
{
perhour++;
while (!line.isempty())
{
line.dequeue(temp);
}
min_per_cust = MIN_PER_HR / perhour;
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{
if (line.isfull())
turnaways++;
else
{
customers++;
temp.set(cycle); // cycle = time of arrival
line.enqueue(temp); // add newcomer to line
}
}
if (wait_time <= 0 && !line.isempty())
{
line.dequeue(temp); // attend next customer
wait_time = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time > 0)
wait_time--;
sum_line += line.queuecount();
}
// reporting results
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";
avetime = (double)line_wait / served;
}
cout << "When there comes " << perhour
<< " people per hour, the average wait time will be about 1 minute.\n";
cout << "Done!\n";
system("pause");
return 0;
}
// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}
运行结果:
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.5>g++ queue.cpp main.cpp -o main
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.5>main
Case Study: Bank of Heather Automatic Teller
Enter maximum size of queue: 100
The simulation hours: The average number of customers per hour: customers accepted: 206
customers served: 206
turnaways: 0
average queue size: 0.00
average wait time: 0.06 minutes
customers accepted: 497
customers served: 497
turnaways: 0
average queue size: 0.01
average wait time: 0.08 minutes
customers accepted: 864
customers served: 864
turnaways: 0
average queue size: 0.01
average wait time: 0.08 minutes
customers accepted: 1364
customers served: 1364
turnaways: 0
average queue size: 0.02
average wait time: 0.09 minutes
customers accepted: 1966
customers served: 1966
turnaways: 0
average queue size: 0.04
average wait time: 0.13 minutes
customers accepted: 2651
customers served: 2651
turnaways: 0
average queue size: 0.06
average wait time: 0.15 minutes
customers accepted: 3480
customers served: 3480
turnaways: 0
average queue size: 0.10
average wait time: 0.17 minutes
customers accepted: 4411
customers served: 4411
turnaways: 0
average queue size: 0.16
average wait time: 0.21 minutes
customers accepted: 5409
customers served: 5409
turnaways: 0
average queue size: 0.22
average wait time: 0.24 minutes
customers accepted: 6489
customers served: 6489
turnaways: 0
average queue size: 0.29
average wait time: 0.27 minutes
customers accepted: 7667
customers served: 7667
turnaways: 0
average queue size: 0.37
average wait time: 0.29 minutes
customers accepted: 8962
customers served: 8962
turnaways: 0
average queue size: 0.48
average wait time: 0.32 minutes
customers accepted: 10382
customers served: 10382
turnaways: 0
average queue size: 0.64
average wait time: 0.37 minutes
customers accepted: 11860
customers served: 11860
turnaways: 0
average queue size: 0.80
average wait time: 0.41 minutes
customers accepted: 13393
customers served: 13393
turnaways: 0
average queue size: 0.96
average wait time: 0.43 minutes
customers accepted: 15134
customers served: 15134
turnaways: 0
average queue size: 1.22
average wait time: 0.48 minutes
customers accepted: 16949
customers served: 16949
turnaways: 0
average queue size: 1.45
average wait time: 0.51 minutes
customers accepted: 18825
customers served: 18825
turnaways: 0
average queue size: 1.82
average wait time: 0.58 minutes
customers accepted: 20781
customers served: 20781
turnaways: 0
average queue size: 2.25
average wait time: 0.65 minutes
customers accepted: 22881
customers served: 22879
turnaways: 0
average queue size: 2.80
average wait time: 0.73 minutes
customers accepted: 25060
customers served: 25058
turnaways: 0
average queue size: 3.53
average wait time: 0.84 minutes
customers accepted: 27314
customers served: 27310
turnaways: 0
average queue size: 4.23
average wait time: 0.93 minutes
customers accepted: 29705
customers served: 29701
turnaways: 0
average queue size: 5.13
average wait time: 1.04 minutes
When there comes 24.00 people per hour, the average wait time will be about 1 minute.
Done!
请按任意键继续. . .
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.5>
6. 再开设一台ATM,重新求解第五题
Heather银行想知道,如果再开设一台ATM,情况将如何。请对模拟进行修改,以包含两个队列。假设当第一台ATM前的排队人数少于第二台ATM时,客户将排在第一队,否则将排在第二队。然后再找出要使平均等候时间为1分钟,每小时到达的客户数应该为多少(注意,这是一个非线性问题,即将ATM数量加倍,并不能保证每小时处理的客户数量也翻倍,并确保客户等候的时间少于1分钟)?
代码:
queue.h和queue.cpp与第五题相同。
main.cpp:
#include "queue.h"
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
const int MIN_PER_HR = 60;
bool newcustomer(double x); // is there a new customer?
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs;
Queue line1(qs); // line queue holds up to qs people
Queue line2(qs);
cout << "The simulation hours: ";
int hours = 100;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "The average number of customers per hour: ";
double perhour = 1;
double min_per_cust; // average time between arrivals
Item temp; // new customer data
long turnaways = 0; // turned away by full queue
long customers = 0; // joined the queue
long served = 0; // served during the simulation
long sum_line = 0; // cumulative line length
int wait_time1 = 0; // time until autoteller is free
int wait_time2 = 0;
int line1_size = 0;
int line2_size = 0;
long line_wait = 0; // cumulative time in line
double avetime = 0;
// running the simulation
while (avetime <= 1)
{
perhour++;
while (!line1.isempty())
{
line1.dequeue(temp);
}
while (!line2.isempty())
{
line2.dequeue(temp);
}
min_per_cust = MIN_PER_HR / perhour;
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{
if (line1.isfull() && line2.isfull())
turnaways++;
else if (line1_size < line2_size)
{
customers++;
temp.set(cycle); // cycle = time of arrival
line1.enqueue(temp); // add newcomer to line
line1_size++;
}
else
{
customers++;
temp.set(cycle); // cycle = time of arrival
line2.enqueue(temp); // add newcomer to line
line2_size++;
}
}
if (wait_time1 <= 0 && !line1.isempty())
{
line1.dequeue(temp); // attend next customer
line1_size--;
wait_time1 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time2 <= 0 && !line2.isempty())
{
line2.dequeue(temp); // attend next customer
line2_size--;
wait_time2 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time1 > 0)
wait_time1--;
if (wait_time2 > 0)
wait_time2--;
sum_line += line1.queuecount();
sum_line += line2.queuecount();
}
// reporting results
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";
avetime = (double)line_wait / served;
}
cout << "When there comes " << perhour
<< " people per hour, the average wait time will be about 1 minute.\n";
cout << "Done!\n";
system("pause");
return 0;
}
// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}
运行结果:
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.6>g++ queue.cpp main.cpp -o main
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.6>main
Case Study: Bank of Heather Automatic Teller
Enter maximum size of queue: 100
The simulation hours: The average number of customers per hour: customers accepted: 211
customers served: 211
turnaways: 0
average queue size: 0.00
average wait time: 0.02 minutes
customers accepted: 499
customers served: 499
turnaways: 0
average queue size: 0.00
average wait time: 0.05 minutes
customers accepted: 886
customers served: 886
turnaways: 0
average queue size: 0.01
average wait time: 0.06 minutes
customers accepted: 1397
customers served: 1397
turnaways: 0
average queue size: 0.02
average wait time: 0.09 minutes
customers accepted: 2025
customers served: 2025
turnaways: 0
average queue size: 0.03
average wait time: 0.10 minutes
customers accepted: 2719
customers served: 2719
turnaways: 0
average queue size: 0.05
average wait time: 0.12 minutes
customers accepted: 3487
customers served: 3487
turnaways: 0
average queue size: 0.07
average wait time: 0.13 minutes
customers accepted: 4367
customers served: 4367
turnaways: 0
average queue size: 0.10
average wait time: 0.14 minutes
customers accepted: 5406
customers served: 5406
turnaways: 0
average queue size: 0.13
average wait time: 0.15 minutes
customers accepted: 6509
customers served: 6509
turnaways: 0
average queue size: 0.17
average wait time: 0.16 minutes
customers accepted: 7761
customers served: 7761
turnaways: 0
average queue size: 0.22
average wait time: 0.17 minutes
customers accepted: 9022
customers served: 9022
turnaways: 0
average queue size: 0.27
average wait time: 0.18 minutes
customers accepted: 10438
customers served: 10438
turnaways: 0
average queue size: 0.33
average wait time: 0.19 minutes
customers accepted: 11966
customers served: 11966
turnaways: 0
average queue size: 0.41
average wait time: 0.21 minutes
customers accepted: 13507
customers served: 13507
turnaways: 0
average queue size: 0.49
average wait time: 0.22 minutes
customers accepted: 15210
customers served: 15210
turnaways: 0
average queue size: 0.58
average wait time: 0.23 minutes
customers accepted: 16913
customers served: 16913
turnaways: 0
average queue size: 0.68
average wait time: 0.24 minutes
customers accepted: 18764
customers served: 18764
turnaways: 0
average queue size: 0.78
average wait time: 0.25 minutes
customers accepted: 20777
customers served: 20777
turnaways: 0
average queue size: 0.91
average wait time: 0.26 minutes
customers accepted: 22736
customers served: 22736
turnaways: 0
average queue size: 1.03
average wait time: 0.27 minutes
customers accepted: 24940
customers served: 24940
turnaways: 0
average queue size: 1.17
average wait time: 0.28 minutes
customers accepted: 27232
customers served: 27232
turnaways: 0
average queue size: 1.33
average wait time: 0.29 minutes
customers accepted: 29676
customers served: 29676
turnaways: 0
average queue size: 1.51
average wait time: 0.31 minutes
customers accepted: 32220
customers served: 32219
turnaways: 0
average queue size: 1.70
average wait time: 0.32 minutes
customers accepted: 34785
customers served: 34784
turnaways: 0
average queue size: 1.90
average wait time: 0.33 minutes
customers accepted: 37465
customers served: 37464
turnaways: 0
average queue size: 2.11
average wait time: 0.34 minutes
customers accepted: 40259
customers served: 40258
turnaways: 0
average queue size: 2.32
average wait time: 0.35 minutes
customers accepted: 43159
customers served: 43158
turnaways: 0
average queue size: 2.55
average wait time: 0.35 minutes
customers accepted: 46104
customers served: 46103
turnaways: 0
average queue size: 2.80
average wait time: 0.36 minutes
customers accepted: 49130
customers served: 49129
turnaways: 0
average queue size: 3.06
average wait time: 0.37 minutes
customers accepted: 52229
customers served: 52228
turnaways: 0
average queue size: 3.32
average wait time: 0.38 minutes
customers accepted: 55535
customers served: 55534
turnaways: 0
average queue size: 3.62
average wait time: 0.39 minutes
customers accepted: 58864
customers served: 58863
turnaways: 0
average queue size: 3.93
average wait time: 0.40 minutes
customers accepted: 62352
customers served: 62350
turnaways: 0
average queue size: 4.25
average wait time: 0.41 minutes
customers accepted: 65932
customers served: 65929
turnaways: 0
average queue size: 4.60
average wait time: 0.42 minutes
customers accepted: 69614
customers served: 69610
turnaways: 0
average queue size: 5.61
average wait time: 0.48 minutes
customers accepted: 73401
customers served: 73397
turnaways: 0
average queue size: 6.01
average wait time: 0.49 minutes
customers accepted: 77283
customers served: 77279
turnaways: 0
average queue size: 6.42
average wait time: 0.50 minutes
customers accepted: 81285
customers served: 81280
turnaways: 0
average queue size: 6.86
average wait time: 0.51 minutes
customers accepted: 85394
customers served: 85389
turnaways: 0
average queue size: 7.31
average wait time: 0.51 minutes
customers accepted: 89599
customers served: 89594
turnaways: 0
average queue size: 7.77
average wait time: 0.52 minutes
customers accepted: 93875
customers served: 93869
turnaways: 0
average queue size: 8.27
average wait time: 0.53 minutes
customers accepted: 98286
customers served: 98278
turnaways: 0
average queue size: 9.63
average wait time: 0.59 minutes
customers accepted: 102838
customers served: 102829
turnaways: 0
average queue size: 11.07
average wait time: 0.65 minutes
customers accepted: 107435
customers served: 107425
turnaways: 0
average queue size: 11.68
average wait time: 0.65 minutes
customers accepted: 112178
customers served: 112168
turnaways: 0
average queue size: 12.35
average wait time: 0.66 minutes
customers accepted: 116951
customers served: 116940
turnaways: 0
average queue size: 13.03
average wait time: 0.67 minutes
customers accepted: 121796
customers served: 121784
turnaways: 0
average queue size: 14.60
average wait time: 0.72 minutes
customers accepted: 126770
customers served: 126758
turnaways: 0
average queue size: 15.38
average wait time: 0.73 minutes
customers accepted: 131867
customers served: 131854
turnaways: 0
average queue size: 16.23
average wait time: 0.74 minutes
customers accepted: 137024
customers served: 137010
turnaways: 0
average queue size: 17.14
average wait time: 0.75 minutes
customers accepted: 142353
customers served: 142337
turnaways: 0
average queue size: 19.18
average wait time: 0.81 minutes
customers accepted: 147727
customers served: 147710
turnaways: 0
average queue size: 20.30
average wait time: 0.82 minutes
customers accepted: 153207
customers served: 153190
turnaways: 0
average queue size: 21.54
average wait time: 0.84 minutes
customers accepted: 158819
customers served: 158799
turnaways: 0
average queue size: 23.25
average wait time: 0.88 minutes
customers accepted: 164531
customers served: 164506
turnaways: 0
average queue size: 25.93
average wait time: 0.95 minutes
customers accepted: 170320
customers served: 170287
turnaways: 0
average queue size: 28.95
average wait time: 1.02 minutes
When there comes 58.00 people per hour, the average wait time will be about 1 minute.
Done!
请按任意键继续. . .
C:\Users\81228\Documents\Program\VScode C++ Program\chapter12\12.6>