> 文章列表 > 《C++ Primer Plus》(第6版)第12章编程练习

《C++ Primer Plus》(第6版)第12章编程练习

《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;
}

运行结果:

《C++ Primer Plus》(第6版)第12章编程练习

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;elsecout << "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;elsecout << "Try again!\\n";}cout << "Bye\\n";system("pause");return 0;
}

运行结果:

《C++ Primer Plus》(第6版)第12章编程练习

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;}elseshares = 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 formatos.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;elsereturn *this;
}

usestock.cpp:

#include "stock.h"
#include <iostream>const int STKS = 4;int main()
{{// create an array of initialized objectsStock 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 elementconst Stock *top = &stocks[0];for (st = 1; st < STKS; st++)top = &top->topval(stocks[st]);// now top points to the most valuable holdingstd::cout << "\\nMost valuable holding:\\n";std::cout << *top;}system("pause");return 0;
}

运行结果:

《C++ Primer Plus》(第6版)第12章编程练习

4. Stack类

请看下面程序清单10.10定义的Stack类的变量:

typedef unsigned long Item;class Stack
{
private:enum{MAX = 10};            // constant specific to classItem *pitems; // holds stack itemsint 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 otherwisebool push(const Item &item); // add item to stack// pop() returns false if stack already is empty, true otherwisebool pop(Item &item); // pop top into itemStack &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 classItem *pitems; // holds stack itemsint 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 otherwisebool push(const Item &item); // add item to stack// pop() returns false if stack already is empty, true otherwisebool pop(Item &item); // pop top into itemStack &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;}elsereturn false;
}
bool Stack::pop(Item &item)
{if (top > 0){item = pitems[--top];return true;}elsereturn 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;
}

运行结果:

《C++ Primer Plus》(第6版)第12章编程练习

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 customerint 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 classstruct Node{Item item;struct Node *next;};enum{Q_SIZE = 10};// private class membersNode *front;     // pointer to front of QueueNode *rear;      // pointer to rear of Queueint items;       // current number of items in Queueconst int qsize; // maximum number of items in Queue// preemptive definitions to prevent public copyingQueue(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 endbool 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 nullptritems = 0;
}Queue::~Queue()
{Node *temp;while (front != NULL) // while queue is not yet empty{temp = front;        // save address of front itemfront = front->next; // reset pointer to next itemdelete 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 exceptionadd->item = item;     // set node pointersadd->next = NULL;     // or nullptr;items++;if (front == NULL) // if queue is empty,front = add;   // place item at frontelserear->next = add; // else place at rearrear = add;           // have rear point to new nodereturn 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 queueitems--;Node *temp = front;  // save location of first itemfront = front->next; // reset front to next itemdelete temp;         // delete former first itemif (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 upstd::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 peoplecout << "The simulation hours: ";int hours = 100;// simulation will run 1 cycle per minutelong cyclelimit = MIN_PER_HR * hours; // # of cyclescout << "The average number of customers per hour: ";double perhour = 1;double min_per_cust; //  average time between arrivalsItem temp;          //  new customer datalong turnaways = 0; //  turned away by full queuelong customers = 0; //  joined the queuelong served = 0;    //  served during the simulationlong sum_line = 0;  //  cumulative line lengthint wait_time = 0;  //  time until autoteller is freelong line_wait = 0; //  cumulative time in linedouble avetime = 0;// running the simulationwhile (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 arrivalline.enqueue(temp); // add newcomer to line}}if (wait_time <= 0 && !line.isempty()){line.dequeue(temp);       // attend next customerwait_time = temp.ptime(); // for wait_time minutesline_wait += cycle - temp.when();served++;}if (wait_time > 0)wait_time--;sum_line += line.queuecount();}// reporting resultsif (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";}elsecout << "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 mainC:\\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: 206customers served: 206turnaways: 0
average queue size: 0.00average wait time: 0.06 minutes
customers accepted: 497customers served: 497turnaways: 0
average queue size: 0.01average wait time: 0.08 minutes
customers accepted: 864customers served: 864turnaways: 0
average queue size: 0.01average wait time: 0.08 minutes
customers accepted: 1364customers served: 1364turnaways: 0
average queue size: 0.02average wait time: 0.09 minutes
customers accepted: 1966customers served: 1966turnaways: 0
average queue size: 0.04average wait time: 0.13 minutes
customers accepted: 2651customers served: 2651turnaways: 0
average queue size: 0.06average wait time: 0.15 minutes
customers accepted: 3480customers served: 3480turnaways: 0
average queue size: 0.10average wait time: 0.17 minutes
customers accepted: 4411customers served: 4411turnaways: 0
average queue size: 0.16average wait time: 0.21 minutes
customers accepted: 5409customers served: 5409turnaways: 0
average queue size: 0.22average wait time: 0.24 minutes
customers accepted: 6489customers served: 6489turnaways: 0
average queue size: 0.29average wait time: 0.27 minutes
customers accepted: 7667customers served: 7667turnaways: 0
average queue size: 0.37average wait time: 0.29 minutes
customers accepted: 8962customers served: 8962turnaways: 0
average queue size: 0.48average wait time: 0.32 minutes
customers accepted: 10382customers served: 10382turnaways: 0
average queue size: 0.64average wait time: 0.37 minutes
customers accepted: 11860customers served: 11860turnaways: 0
average queue size: 0.80average wait time: 0.41 minutes
customers accepted: 13393customers served: 13393turnaways: 0
average queue size: 0.96average wait time: 0.43 minutes
customers accepted: 15134customers served: 15134turnaways: 0
average queue size: 1.22average wait time: 0.48 minutes
customers accepted: 16949customers served: 16949turnaways: 0
average queue size: 1.45average wait time: 0.51 minutes
customers accepted: 18825customers served: 18825turnaways: 0
average queue size: 1.82average wait time: 0.58 minutes
customers accepted: 20781customers served: 20781turnaways: 0
average queue size: 2.25average wait time: 0.65 minutes
customers accepted: 22881customers served: 22879turnaways: 0
average queue size: 2.80average wait time: 0.73 minutes
customers accepted: 25060customers served: 25058turnaways: 0
average queue size: 3.53average wait time: 0.84 minutes
customers accepted: 27314customers served: 27310turnaways: 0
average queue size: 4.23average wait time: 0.93 minutes
customers accepted: 29705customers served: 29701turnaways: 0
average queue size: 5.13average 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 upstd::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 peopleQueue line2(qs);cout << "The simulation hours: ";int hours = 100;// simulation will run 1 cycle per minutelong cyclelimit = MIN_PER_HR * hours; // # of cyclescout << "The average number of customers per hour: ";double perhour = 1;double min_per_cust; //  average time between arrivalsItem temp;          //  new customer datalong turnaways = 0; //  turned away by full queuelong customers = 0; //  joined the queuelong served = 0;    //  served during the simulationlong sum_line = 0;  //  cumulative line lengthint wait_time1 = 0; //  time until autoteller is freeint wait_time2 = 0;int line1_size = 0;int line2_size = 0;long line_wait = 0; //  cumulative time in linedouble avetime = 0;// running the simulationwhile (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 arrivalline1.enqueue(temp); // add newcomer to lineline1_size++;}else{customers++;temp.set(cycle);     // cycle = time of arrivalline2.enqueue(temp); // add newcomer to lineline2_size++;}}if (wait_time1 <= 0 && !line1.isempty()){line1.dequeue(temp); // attend next customerline1_size--;wait_time1 = temp.ptime(); // for wait_time minutesline_wait += cycle - temp.when();served++;}if (wait_time2 <= 0 && !line2.isempty()){line2.dequeue(temp); // attend next customerline2_size--;wait_time2 = temp.ptime(); // for wait_time minutesline_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 resultsif (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";}elsecout << "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 mainC:\\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: 211customers served: 211turnaways: 0
average queue size: 0.00average wait time: 0.02 minutes
customers accepted: 499customers served: 499turnaways: 0
average queue size: 0.00average wait time: 0.05 minutes
customers accepted: 886customers served: 886turnaways: 0
average queue size: 0.01average wait time: 0.06 minutes
customers accepted: 1397customers served: 1397turnaways: 0
average queue size: 0.02average wait time: 0.09 minutes
customers accepted: 2025customers served: 2025turnaways: 0
average queue size: 0.03average wait time: 0.10 minutes
customers accepted: 2719customers served: 2719turnaways: 0
average queue size: 0.05average wait time: 0.12 minutes
customers accepted: 3487customers served: 3487turnaways: 0
average queue size: 0.07average wait time: 0.13 minutes
customers accepted: 4367customers served: 4367turnaways: 0
average queue size: 0.10average wait time: 0.14 minutes
customers accepted: 5406customers served: 5406turnaways: 0
average queue size: 0.13average wait time: 0.15 minutes
customers accepted: 6509customers served: 6509turnaways: 0
average queue size: 0.17average wait time: 0.16 minutes
customers accepted: 7761customers served: 7761turnaways: 0
average queue size: 0.22average wait time: 0.17 minutes
customers accepted: 9022customers served: 9022turnaways: 0
average queue size: 0.27average wait time: 0.18 minutes
customers accepted: 10438customers served: 10438turnaways: 0
average queue size: 0.33average wait time: 0.19 minutes
customers accepted: 11966customers served: 11966turnaways: 0
average queue size: 0.41average wait time: 0.21 minutes
customers accepted: 13507customers served: 13507turnaways: 0
average queue size: 0.49average wait time: 0.22 minutes
customers accepted: 15210customers served: 15210turnaways: 0
average queue size: 0.58average wait time: 0.23 minutes
customers accepted: 16913customers served: 16913turnaways: 0
average queue size: 0.68average wait time: 0.24 minutes
customers accepted: 18764customers served: 18764turnaways: 0
average queue size: 0.78average wait time: 0.25 minutes
customers accepted: 20777customers served: 20777turnaways: 0
average queue size: 0.91average wait time: 0.26 minutes
customers accepted: 22736customers served: 22736turnaways: 0
average queue size: 1.03average wait time: 0.27 minutes
customers accepted: 24940customers served: 24940turnaways: 0
average queue size: 1.17average wait time: 0.28 minutes
customers accepted: 27232customers served: 27232turnaways: 0
average queue size: 1.33average wait time: 0.29 minutes
customers accepted: 29676customers served: 29676turnaways: 0
average queue size: 1.51average wait time: 0.31 minutes
customers accepted: 32220customers served: 32219turnaways: 0
average queue size: 1.70average wait time: 0.32 minutes
customers accepted: 34785customers served: 34784turnaways: 0
average queue size: 1.90average wait time: 0.33 minutes
customers accepted: 37465customers served: 37464turnaways: 0
average queue size: 2.11average wait time: 0.34 minutes
customers accepted: 40259customers served: 40258turnaways: 0
average queue size: 2.32average wait time: 0.35 minutes
customers accepted: 43159customers served: 43158turnaways: 0
average queue size: 2.55average wait time: 0.35 minutes
customers accepted: 46104customers served: 46103turnaways: 0
average queue size: 2.80average wait time: 0.36 minutes
customers accepted: 49130customers served: 49129turnaways: 0
average queue size: 3.06average wait time: 0.37 minutes
customers accepted: 52229customers served: 52228turnaways: 0
average queue size: 3.32average wait time: 0.38 minutes
customers accepted: 55535customers served: 55534turnaways: 0
average queue size: 3.62average wait time: 0.39 minutes
customers accepted: 58864customers served: 58863turnaways: 0
average queue size: 3.93average wait time: 0.40 minutes
customers accepted: 62352customers served: 62350turnaways: 0
average queue size: 4.25average wait time: 0.41 minutes
customers accepted: 65932customers served: 65929turnaways: 0
average queue size: 4.60average wait time: 0.42 minutes
customers accepted: 69614customers served: 69610turnaways: 0
average queue size: 5.61average wait time: 0.48 minutes
customers accepted: 73401customers served: 73397turnaways: 0
average queue size: 6.01average wait time: 0.49 minutes
customers accepted: 77283customers served: 77279turnaways: 0
average queue size: 6.42average wait time: 0.50 minutes
customers accepted: 81285customers served: 81280turnaways: 0
average queue size: 6.86average wait time: 0.51 minutes
customers accepted: 85394customers served: 85389turnaways: 0
average queue size: 7.31average wait time: 0.51 minutes
customers accepted: 89599customers served: 89594turnaways: 0
average queue size: 7.77average wait time: 0.52 minutes
customers accepted: 93875customers served: 93869turnaways: 0
average queue size: 8.27average wait time: 0.53 minutes
customers accepted: 98286customers served: 98278turnaways: 0
average queue size: 9.63average wait time: 0.59 minutes
customers accepted: 102838customers served: 102829turnaways: 0
average queue size: 11.07average wait time: 0.65 minutes
customers accepted: 107435customers served: 107425turnaways: 0
average queue size: 11.68average wait time: 0.65 minutes
customers accepted: 112178customers served: 112168turnaways: 0
average queue size: 12.35average wait time: 0.66 minutes
customers accepted: 116951customers served: 116940turnaways: 0
average queue size: 13.03average wait time: 0.67 minutes
customers accepted: 121796customers served: 121784turnaways: 0
average queue size: 14.60average wait time: 0.72 minutes
customers accepted: 126770customers served: 126758turnaways: 0
average queue size: 15.38average wait time: 0.73 minutes
customers accepted: 131867customers served: 131854turnaways: 0
average queue size: 16.23average wait time: 0.74 minutes
customers accepted: 137024customers served: 137010turnaways: 0
average queue size: 17.14average wait time: 0.75 minutes
customers accepted: 142353customers served: 142337turnaways: 0
average queue size: 19.18average wait time: 0.81 minutes
customers accepted: 147727customers served: 147710turnaways: 0
average queue size: 20.30average wait time: 0.82 minutes
customers accepted: 153207customers served: 153190turnaways: 0
average queue size: 21.54average wait time: 0.84 minutes
customers accepted: 158819customers served: 158799turnaways: 0
average queue size: 23.25average wait time: 0.88 minutes
customers accepted: 164531customers served: 164506turnaways: 0
average queue size: 25.93average wait time: 0.95 minutes
customers accepted: 170320customers served: 170287turnaways: 0
average queue size: 28.95average 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>