C++ Primer Plus(第六版)第12章课后编程答案

本文提供了C++ Primer Plus第六版第12章的课后编程题答案,包括程序清单12-10、12-11和12-12的详细解答,并给出了不同的解题思路,读者可以通过输入(10,100,18)进行测试。" 44213413,4960755,C++实现表达式求值程序,"['C++编程', '算法', '数据结构', '表达式解析']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

#ifndef QUEUE_H_
#define QUEUE_H_

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

#endif
#include"queue.h"
#include<iostream>
#include<cstring>
using namespace std;

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

Cow::Cow(const char *num, const char *ho, double wt)
{
	strcpy_s(name, num);
	int len;
	len = strlen(ho);
	hobby = new char[len + 1];
	strcpy_s(hobby, len+1,ho);
	weight = wt;
}

Cow::Cow(const Cow & c)
{
	strcpy_s(name, c.name);
	int len;
	len = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby,len+1, c.hobby);
	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 = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby,len+1,c.hobby);
	strcpy_s(name, c.name);
	return *this;
}
 
void Cow::ShowCow() const
{
	cout << "Name:" << name << endl;
	cout << "Hobby:" << hobby << endl;
	cout << "Weight:" << weight << endl;
	cout << endl;
}
#include<iostream>
#include<cstring>
#include<string>
#include"queue.h"

using namespace std;

int main()
{
	Cow a;
	a.ShowCow();
	Cow b("huangfu", "sleep", 100);
	b.ShowCow();
	Cow c("shuyun", "run", 200);
	c.ShowCow();
	a = c;
	a.ShowCow();

	system("PAUSE");
	return 0;
}

2.

#ifndef QUEUE_H_
#define QUEUE_H_
#include <iostream>
using std::ostream;
using std::istream;

class String
{
private:
	char * str;             // pointer to string
	int len;                // length of string
	static int num_strings; // number of objects
	static const int CINLIM = 80;  // cin input limit
public:
	// constructors and other methods
	String(const char * s); // constructor
	String();               // default constructor
	String(const String &); // copy constructor
	~String();              // destructor
	int length() const { return len; }

	//新载函数
	void stringlow();
	void stringup();
	int has(char c);
	friend String operator+(const String &st1, const String &st2);

	// overloaded operator methods    
	String & operator=(const String &);
	String & operator=(const char *);
	char & operator[](int i);
	const char & operator[](int i) const;

	// overloaded operator friends
	friend bool operator<(const String &st, const String &st2);
	friend bool operator>(const String &st1, 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);
	// static function
	static int HowMany();
};
#endif
#include"queue.h"
#include<cctype>
#include<cstring>

using std::cin;
using std::cout;

// initializing static class member

int String::num_strings = 0;       //初始化应该在方法文件中,不在类声明中,不需使用static

// static method
int String::HowMany()          //静态成员函数
{
	return num_strings;
}

// class methods
String::String(const char * s)     // construct String from C string
{
	len = std::strlen(s);          // set size
	str = new char[len + 1];       // allot storage
	strcpy_s(str,len+1, s);           // initialize pointer
	num_strings++;                 // set object count
}

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

String::String(const String & st)
{
	num_strings++;             // handle static member update
	len = st.len;              // same length
	str = new char[len + 1];  // allot space
	strcpy_s(str, len+1,st.str);  // copy string to new location
}

String::~String()                     // necessary destructor
{
	--num_strings;                    // required
	delete[] str;                    // required
}

// overloaded operator methods    

// assign a String to a String
String & String::operator=(const String & st)
{
	if (this == &st)
		return *this;
	delete[] str;
	len = st.len;
	str = new char[len + 1];
	strcpy_s(str,len+1, st.str);
	return *this;
}

// assign a C string to a String
String & String::operator=(const char * s)
{
	delete[] str;
	len = std::strlen(s);
	str = new char[len + 1];
	strcpy_s(str,len+1, s);
	return *this;
}

// read-write char access for non-const String
char & String::operator[](int i)
{
	return str[i];
}

// read-only char access for const String
const char & String::operator[](int i) const
{
	return str[i];
}

// overloaded operator friends

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

// simple String output
ostream & operator<<(ostream & os, const String & st)
{
	os << st.str;
	return os;
}

// quick and dirty String input
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.length + st2.length;
	// 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"queue.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.

// stock20.h -- augmented version
#ifndef STOCK20_H_
#define STOCK20_H_
#include<iostream>

class Stock
{
private:
    char * company;
    int shares;
    double share_val;
    double total_val;
    void set_tot() { total_val = shares * share_val; }
public:
    Stock();        // default constructor
    Stock(const char* co, long n = 0, double pr = 0.0);
    ~Stock();       // do-nothing destructor
    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);      /*void show()const;*/
};

#endif
// stock20.cpp -- augmented version
#include "stock20.h"
#include<cstring>
using namespace std;

// constructors
Stock::Stock()        // default constructor
{
	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;
	len = strlen(co);
	company = new char[len + 1];
	strcpy_s(company,len+1, 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();
}

// class destructor
Stock::~Stock()        // quiet class destructor
{
	delete[] company;
}

// other methods
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 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();
}

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;
}
//void Stock::show() const
//{
//    using std::cout;
//    using std::ios_base;
//    // set format to #.###
//    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 << "  Share Price: $" << share_val;
//    // set format to #.##
//    cout.precision(2);
//    cout << "  Total Worth: $" << total_val << '\n';
//
//    // restore original format
//    cout.setf(orig, ios_base::floatfield);
//    cout.precision(prec);
//}
// usestok2.cpp -- using the Stock class
// compile with stock20.cpp
#include <iostream>
#include "stock20.h"

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;
    // std::cin.get();
    return 0; 
}

4.

// stack.h -- class definition for the stack ADT
#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;            //number of elements in stack
    int top;            // index for top stack item
public:
    Stack(int n=MAX);      //creates stack with n elements
	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 -- Stack member functions
#include "stack.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;
}
// stacker.cpp -- testing the Stack class
#include <iostream>
#include "stack.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)进行测试

// queue.h -- interface for a queue
#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 -- Queue and Customer methods
#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; 
}
// bank.cpp -- using the Queue interface
// compile with queue.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 << "Enter the number of simulation hours: ";
    int hours;              //  hours of simulation
    cin >> hours;
    // simulation will run 1 cycle per minute
    long cyclelimit = MIN_PER_HR * hours; // # of cycles

    cout << "Enter the average number of customers per hour: ";
    double perhour;         //  average # of arrival per hour
    cin >> perhour;
    double min_per_cust;    //  average time between arrivals
    min_per_cust = MIN_PER_HR / perhour;

    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


// running the simulation
    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";
    cout << "Done!\n";
    // cin.get();
    // cin.get();
    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); 
}

6.

// queue.h -- interface for a queue
#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
	friend bool operator>(const Queue & item1, const Queue & item2);
};
#endif
// queue.cpp -- Queue and Customer methods
#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;
}

//比较人数
bool operator>(const Queue & item1, const Queue & item2)
{
	return item1.items > item2.items;
}


// 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; 
}
// bank.cpp -- 建立两个队列进行计算
// compile with queue.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 line1(qs);         // line queue holds up to qs people
	Queue line2(qs);         //分成两个队伍进行计算

    cout << "Enter the number of simulation hours: ";
    int hours;              //  hours of simulation
    cin >> hours;
    // simulation will run 1 cycle per minute
    long cyclelimit = MIN_PER_HR * hours; // # of cycles

    cout << "Enter the average number of customers per hour: ";
    double perhour;         //  average # of arrival per hour
    cin >> perhour;
    double min_per_cust;    //  average time between arrivals
    min_per_cust = MIN_PER_HR / perhour;

    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 wait1_time = 0;      //  time until autoteller is free
	int wait2_time = 0;
    long line1_wait = 0;     //  cumulative time in line
	long line2_wait = 0;     


// running the simulation
    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))  // have newcomer
        {
            if (line1.isfull()&&line2.isfull())
                turnaways++;
            else if(line2>line1||line1.isfull())
            {
                customers++;
                temp.set(cycle);    // cycle = time of arrival
                line1.enqueue(temp); // add newcomer to line1
            }
			else 
			{
				customers++;
				temp.set(cycle);    // cycle = time of arrival
				line2.enqueue(temp); // add newcomer to line2
			}
        }
        if (wait1_time <= 0 && !line1.isempty())
        {
            line1.dequeue (temp);      // attend next customer
            wait1_time = temp.ptime(); // for wait_time minutes
            line1_wait += cycle - temp.when();
            served++;
        }
		if (wait2_time <= 0 && !line2.isempty())
		{
			line2.dequeue(temp);      // attend next customer
			wait2_time = temp.ptime(); // for wait_time minutes
			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();
    }

// 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) (line1_wait+line2_wait) / served << " minutes\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";
    // cin.get();
    // cin.get();
    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); 
}

另一种方法:

#include<iostream>
#include<cstdlib>
#include<ctime>
#include"queue.h"
const int MIN_PER_HR = 60;

bool newCustomer(double x)     //每隔x次,rand()/RAND_max会有一次值<1
{
	return (std::rand()*x / RAND_MAX < 1);
}

int main()
{
	using std::cin;
	using std::cout;
	using std::endl;
	using std::ios_base;
	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 sum_line = 0;
	int wait_time = 0;
	int wait_time2 = 0;   //等待时间要+1个
	long line_wait = 0;

	for (int cycle = 0; cycle < cyclelimit; cycle++)    //cycle每循环一次,代表过了一分钟
	{
		if (newCustomer(min_per_cust))
		{
			if (line.isfull() && line2.isfull())    //当两个队列都满的时候才拒绝服务
				turnaways++;      //拒绝服务的人数
			else
			{
				customers++;   
				temp.set(cycle);    //cycle是到达时间
				if (line.queuecount() >= line2.queuecount())
					line2.enqueue(temp);
				else
					line.enqueue(temp);    
			}
		}
		if (wait_time <= 0 && !line.isempty())   //队列1中有用户处理完业务
		{
			line.dequeue(temp);
			wait_time = temp.ptime();   //wait_time是该客户处理业务所用时间
			line_wait += cycle - temp.when();  //cycle_temp.when()是该客户一共在队列中等待了多久
			served++;     //服务人数+1
		}

		if (wait_time2 <= 0 && !line2.isempty())   //队列1中有用户处理完业务
		{
			line.dequeue(temp);
			wait_time = 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)   //队列1正在处理业务的处理时间-1,因为过了一分钟
			wait_time2--;     //wait_time=temp.ptime()这里随机设置了wait_time
		sum_line += line.queuecount() + line2.queuecount();    //sum_line是队伍总长度,每分钟计算一次队伍长度
	}

// 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";
    cout << "Done!\n";
    // cin.get();
    // cin.get();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值