《C++ Primer Plus(第六版)》(24)(第十二章 类和动态内存分配 编程题和答案)...

1.对于下面的类声明:

    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;
        
    };
给这个类提供实现,并编写一个使用所有成员函数的小程序。

Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#ifndef _Test_H_
#define _Test_H_
#include <iostream>
using namespace std;
namespace FableGame
{
    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
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>
#include <cmath>

using namespace FableGame;

Cow::Cow()
{
    name[0] = '\0';
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0;
}
Cow::Cow(const char * nm, const char* ho, double wt)
{
    strncpy(name, nm, 40);
    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;
    }
    
    strcpy(name, c.name);
    delete[] hobby;
    hobby = new char[strlen(c.hobby) + 1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
    return *this;
}
void Cow::showCow()const
{
    cout << "name: " << name << " hobby: " << hobby << " weight: " << weight << endl;
}
main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Test.h"
#include <fstream>
using namespace std;
using namespace FableGame;
int main()
{
    Cow a;
    Cow b("Mengniu", "niunai", 500);
    Cow c = b;
    
    
    a.showCow();
    b.showCow();
    c.showCow();
    return 0;
}


2.通过完成下面的工作来改进String类声明(即将String1.h升级为String2.h)。

a.对+运算符进行重载,使之可将两个字符串合并成1个。

b.提供一个Stringlow()成员函数,将字符串中所有的字母字符转换成小写(别忘了cctype系列字符函数)。

c.提供String()成员函数,将字符串中所有字母转换成大写。

d.提供一个这样的成员函数,它接受一个char参数,返回该字符在字符串中出现的次数。

使用下面程序来测试您的工作:

//main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include "Test.h"
using namespace std;
using namespace FableGame;
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 ("grean"), 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;
}
修改:

Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#ifndef _Test_H_
#define _Test_H_
#include <iostream>
#include <cctype>
using namespace std;
namespace FableGame
{
    class String
    {
    private:
        char * str;
        size_t len;
        static int num_strings;
        static const int CINLIM = 80;
    public:
        String();
        String(const char * s);
        String(const String& c);
        ~String();
        size_t length() const {return len;}
        void stringlow();
        void stringup();
        int has(const char& ch);
        String & operator=(const String&);
        String & operator=(const char* );
        char& operator[](int i);
        const char& operator[](int i)const;
        friend String operator+(const String& st, const String& st2);
        friend bool operator<(const String& st, const String& st2);
        friend bool operator>(const String& st, const String& st2);
        friend bool operator==(const String& st, const String& st2);
        friend ostream& operator<<(ostream& os, const String& st);
        friend istream& operator>>(istream& is, String& st);
        
        static int HowMany();
    }; 
}
#endif
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>
#include <cstring>

using namespace std;
using namespace FableGame;
int String::num_strings = 0;

int String::HowMany()
{
    return num_strings;
}

String::String(const char* s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);
    num_strings++;
}

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

String::String(const String& st)
{
    num_strings++;
    len = st.len;
    str = new char[len + 1];
    strcpy(str, st.str);
}

String::~String()
{
    --num_strings;
    delete [] str;
}

String & String::operator=(const FableGame::String &st)
{
    if (this == &st) {
        return *this;
    }
    delete [] str;
    len = st.len;
    str = new char[len + 1];
    strcpy(str, st.str);
    return *this;
}

String & String::operator=(const char *s)
{
    delete [] str;
    len = std::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 FableGame::operator<(const String &st1, const String& st2)
{
    return ( std::strcmp(st1.str, st2.str) < 0 );
}

bool FableGame::operator>(const String& st1, const String& st2)
{
    return st2 < st1;
}

bool FableGame::operator==(const String& st1, const String & st2)
{
    return ( std::strcmp(st1.str, st2.str) == 0 );
}

ostream& FableGame::operator<<(ostream& os, const String& st)
{
    os << st.str;
    return os;
}

istream& FableGame::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;
}

String FableGame::operator+(const String& st, const String& st2)
{
    char* ch = new char[strlen(st.str) + strlen(st2.str) + 1];
    std::strcat(ch, st.str);
    std::strcat(ch, st2.str);
    String st3(ch);
    delete[] ch;
    return st3;
}

void FableGame::String::stringlow()
{
    for (int i = 0; i < len; ++i) {
        if(isupper(str[i]))
        {
            str[i] = tolower(str[i]);
        }
    }
}

void FableGame::String::stringup()
{
    for (int i = 0; i < len; ++i) {
        if(islower(str[i]))
        {
            str[i] = toupper(str[i]);
        }
    }
}

int FableGame::String::has(const char& ch)
{
    int total = 0;
    for (int i = 0; i < len; ++i) {
        if (str[i] == ch) {
            ++total;
        }
    }
    return total;
}


3.新编写程序清单10.7和程序清单10.8描述的Stock类,使之使用动态分配内存,而不是string类对象来存储股票名称。另外,使用重载的operator<<()定义代替show()成员函数。再使用程序清单10.9测试新的定义程序。
原来的代码:
Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#ifndef _Test_H_
#define _Test_H_
#include <string>
using namespace std;
namespace FableGame
{
    class Stock
    {
    private:
        std::string company;
        int shares;
        double share_val;
        double total_val;
        void set_tot(){ total_val = shares * share_val; }
      
    public:
        Stock();
        Stock(const std::string& co, int n = 0, double pr = 0.0);
        ~Stock();
        void buy(long num, double price);
        void sell(long num, double price);
        void update(double price);
        void show()const;
        const Stock& topval(const Stock& s) const;
    };  
}
#endif
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>

using namespace std;
using namespace FableGame;

Stock::Stock()
{
    company = "no name";
    shares = 0;
    share_val = 0.0;
    total_val = 0.0;
}

Stock::Stock(const std::string& co, int n, double pr)
{
    company = co;
    if (n < 0) {
        std::cout << "Number of shares can't be negative; " << company << " shares set to 0.\n";
        shares = 0;
    }
    else{
        shares = n;
    }
    share_val = pr;
    set_tot();
}

Stock::~Stock()
{
    
}

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::show() const
{
    ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
    std::streamsize prec = cout.precision(3);
    cout << "Company: " << company << " shares: " << shares << endl;
    cout << "  Share Price: $ " << share_val<< "  Total Worth: $" << total_val << endl;
    cout.setf(orig, ios_base::floatfield);
    cout.precision(prec);
}

const Stock& Stock::topval(const Stock& s) const
{
    if (s.total_val > total_val)
    {
        return s;
    }
    else
    {
        return *this;
    }
}
main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include "Test.h"
using namespace std;
using namespace FableGame;

const int STKS = 4;
int main()
{
    Stock stocks[STKS] = {
        Stock("NanoSmart", 12, 20.0),
        Stock("Boffo Objects", 200, 2.0),
        Stock("Monolithic Obelisks", 130, 3.25),
        Stock("Fleep Enterprises", 60, 6.5)
    };
    cout << "Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; st++) {
        stocks[st].show();
    }
    
    const Stock * top = &stocks[0];
    for (st = 1; st < STKS; ++st) {
        top = &top->topval(stocks[st]);
    }
    cout << "\nMost valuable holding:\n";
    top->show();
    return 0;
}

修改之后的代码:
Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#ifndef _Test_H_
#define _Test_H_
#include <iostream>
using namespace std;
namespace FableGame
{
    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, int n = 0, double pr = 0.0);
        Stock(const Stock& st);
        ~Stock();
        
        Stock& operator=(const Stock&);
        void buy(long num, double price);
        void sell(long num, double price);
        void update(double price);
        friend ostream& operator<<(ostream& os, const Stock& st);
        const Stock& topval(const Stock& s) const;
    };
}
#endif
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>

using namespace std;
using namespace FableGame;

Stock::Stock()
{
    company = new char[8];
    strcpy(company,"no name");
    shares = 0;
    share_val = 0.0;
    total_val = 0.0;
}

Stock::Stock(const char* co, int n, double pr)
{
    company = new char[strlen(co) + 1];
    strcpy(company,co);
    if (n < 0) {
        std::cout << "Number of shares can't be negative; " << company << " shares set to 0.\n";
        shares = 0;
    }
    else{
        shares = n;
    }
    share_val = pr;
    set_tot();
}

Stock::Stock(const Stock& st)
{
    company = new char[strlen(st.company) + 1];
    strcpy(company,st.company);
    shares = st.shares;
    share_val = st.share_val;
    set_tot();
}

Stock::~Stock()
{
    delete [] company;
}

Stock& Stock::operator=(const Stock& st)
{   if(this == &st) return *this;//漏了这一句,要补上
    delete[] company;
    company = new char[strlen(st.company) + 1];
    strcpy(company,st.company);
    shares = st.shares;
    share_val = st.share_val;
    set_tot();
    return *this;
}

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

ostream& FableGame::operator<<(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 << endl;
    os << "  Share Price: $ " << st.share_val<< "  Total Worth: $" << st.total_val << endl;
    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;
    }
}
main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include "Test.h"
using namespace std;
using namespace FableGame;

const int STKS = 4;
int main()
{
    Stock stocks[STKS] = {
        Stock("NanoSmart", 12, 20.0),
        Stock("Boffo Objects", 200, 2.0),
        Stock("Monolithic Obelisks", 130, 3.25),
        Stock("Fleep Enterprises", 60, 6.5)
    };
    cout << "Stock holdings:\n";
    int st;
    for (st = 0; st < STKS; st++) {
        cout << stocks[st];
    }
    
    const Stock * top = &stocks[0];
    for (st = 1; st < STKS; ++st) {
        top = &top->topval(stocks[st]);
    }
    cout << "\nMost valuable holding:\n";
    cout << *top;
    return 0;
}

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

    typedef unsigned long Item;
    class Stack
    {
    private:
        enum {MAX = 10};
        Item * pitems;
        int size;
        int top;
      
    public:
        Stack(int = MAX);
        Stack(const Stack& st);
        ~Stack();
        bool isempty() const;
        bool isfull() const;
        bool push(const Item& item);
        bool pop(Item& item);
        Stack & operator=(const Stack& st);
        
    };
正如私有成员表明的,这个类使用动态分配的数组来保存栈顶。请重新编写方法,以适应这种新的表示法,并编写一个程序来演示所有方法,包括复制构造函数和赋值运算符。

Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#ifndef _Test_H_
#define _Test_H_
#include <iostream>
using namespace std;
namespace FableGame
{
    typedef unsigned long Item;
    class Stack
    {
    private:
        enum {MAX = 10};
        Item * pitems;
        int size;
        int top;
      
    public:
        Stack(int n = MAX);
        Stack(const Stack& st);
        ~Stack();
        bool isempty() const;
        bool isfull() const;
        bool push(const Item& item);
        bool pop(Item& item);
        Stack & operator=(const Stack& st);
        friend ostream& operator<<(ostream& os, const Stack& st);
    };
}
#endif
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>

using namespace std;
using namespace FableGame;

Stack::Stack(int n)
{
    pitems = new Item[n];
    top = 0;
    size = n;
}

Stack::Stack(const Stack& st)
{
    //if (this == &st) {
    //    return;
    //}这个写错了,应该是在下面的
    pitems = new Item[st.size];
    size = st.size;
    top = st.top;
    for (int i = 0; i < size; ++i) {
        pitems[i] = st.pitems[i];
    }
}

Stack & Stack::operator=(const Stack& st)
{   if(this == &st) return *this;
    delete [] pitems;
    pitems = new Item[st.size];
    size = st.size;
    top = st.top;
    for (int i = 0; i < size; ++i) {
        pitems[i] = st.pitems[i];
    }
    return * this;
}

Stack::~Stack()
{
    delete[] pitems;
}

bool Stack::isempty()const
{
    return top == 0;
}

bool Stack::isfull()const
{
    return top == size;
}

bool Stack::push(const Item &item)
{
    if (top < size) {
        pitems[top++] = item;
        return true;
    }
    else{
        return false;
    }
}

bool Stack::pop(Item &item)
{
    if (top > 0) {
        item = pitems[--top];
        return true;
    }
    else{
        return false;
    }
}

ostream& FableGame::operator<<(ostream& os, const Stack& st)
{
    os<<"Stack: \nsize: "<< st.size << " top: "<< st.top << endl;
    for (int i = 0; i < st.top; ++i) {
        os << "item" << i << ": " << st.pitems[i] << endl;
    }
    return os;
}
main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include "Test.h"
using namespace std;
using namespace FableGame;

const int STKS = 4;
int main()
{
    Stack st1;
    st1.push(11111);
    st1.push(22222);
    st1.push(33333);
    
    Stack st2 = Stack(st1);
    st2.push(44444);
    st2.push(55555);
    
    Stack st3;
    st3 = st2;
    Item item;
    st3.pop(item);
    cout<<"pop item: "<< item << endl;
    st3.push(66666);
    
    cout<< st1 << endl;
    cout<< st2 << endl;
    cout<< st3 << endl;
    return 0;
}

5.Heather银行进行研究表明,ATM客户不希望排队时间超过1分钟。使用程序清单12.10中的模拟,找出要使平均等候时间为1分钟,每小时到达客户数应为多少(试验时间不短于100小时)?

Test.h

//
//  Test.h
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#ifndef _Test_H_
#define _Test_H_
#include <iostream>
using namespace std;
namespace FableGame
{
    
    class Customer
    {
    private:
        long arrive;//到达的时间
        int processtime;//处理业务的时间
      
    public:
        Customer() { arrive = processtime = 0; }
        void set(long when);
        long when() const { return arrive; }
        int ptime() const { return processtime; }
    };
    
    typedef Customer Item;
    
    class Queue
    {
    private:
        struct Node
        {
            Item item;
            struct Node * next;
        };
        enum{ Q_SIZE = 10};
        Node* front;
        Node* rear;
        int items;
        const int qsize;
        Queue(const Queue& q):qsize(0) {}
        Queue& operator=(const Queue& q) { return * this;}
    public:
        Queue(int qs = Q_SIZE);
        ~Queue();
        bool isempty() const;
        bool isfull()const;
        int queuecount() const;
        bool enqueue(const Item& item);
        bool dequeue(Item& item);
    };
}
#endif
Test.cpp

//
//  Test.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/21.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//

#include "Test.h"
#include <iostream>
#include <cstdlib>
using namespace std;
using namespace FableGame;

Queue::Queue(int qs): qsize(qs)
{
    front = rear = nullptr;
    items = 0;
}

Queue::~Queue()
{
    Node * temp;
    while (front != nullptr) {
        temp = front;
        front = front->next;
        delete temp;
    }
}

bool Queue::isempty()const
{
    return items == 0;
}
bool Queue::isfull() const
{
    return items == qsize;
}

int Queue::queuecount()const
{
    return items;
}

bool Queue::enqueue(const Item &item)
{
    if (isfull()) {
        return false;
    }
    Node* add = new Node;
    add->item = item;
    add->next = nullptr;
    items++;
    if (front == nullptr) {
        front = add;
    }
    else
    {
        rear->next = add;
    }
    rear = add;
    return true;
}

bool Queue::dequeue(Item &item)
{
    if (front == nullptr) {
        return false;
    }
    item = front->item;
    items--;
    Node* temp = front;
    front = front->next;
    delete temp;
    if (items == 0) {
        rear = nullptr;
    }
    return true;
}

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

main.cpp

#include <iostream>     
#include "Test.h"  
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace FableGame;
 
const int MIN_PER_HR = 60;//每小时的分钟数

bool newcustomer(double x);
int main(int argc, const char * argv[])
{
	srand(time(0));//随机数种子
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue: ";
	int qs;//队列最大长度
	cin >> qs;
	Queue line(qs);

	cout << "Enter the number of simulation hours: ";
	int hours;//模拟的小时数
	cin >> hours;
	int cyclelimit = MIN_PER_HR * hours;//总分钟数限制
	cout << "Enter the average number of customers per hour: ";
	double perhour;//每小时接收的客人
	cin >> perhour;
	double min_per_cust = MIN_PER_HR/perhour;

	Item temp;
	int turnaways = 0;//来了没处理就离开的人
	int customers = 0;//客户数
	int served = 0;//已经服务过的客户数
	int sum_line = 0;//队列总长度
	int wait_time = 0;//正在处理业务时间
	int line_wait = 0;//总的等待时间

	for (int cycle = 0; cycle < cyclelimit; ++cycle)
	{
		if (newcustomer(min_per_cust))
		{
			//有客户来了
			if (line.isfull())
			{
				turnaways++;//队伍满了,离开
			}
			else
			{
				customers++; //增加客户
				temp.set(cycle);
				line.enqueue(temp);//加入队列
			}
		}
		if (wait_time <= 0&& !line.isempty())
		{
			line.dequeue(temp);//处理客户
			wait_time = temp.ptime();
			line_wait += cycle - temp.when();//等待时间
			served++;//服务的客户加1
		}
		if (wait_time > 0)
		{
			wait_time--;//每分钟减1
		}
		sum_line += line.queuecount();//这分钟正在等待的人数
	}
	if (customers > 0)
	{
		cout << "customers accepted: " << customers << endl;
		cout << "customers served: " << served << endl;
		cout << "turnsways: " << 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";

	return 0;
}

//判断客户是否到来
bool newcustomer(double x)
{
	return (rand() * x / RAND_MAX < 1);
} 

修改后的:::::::::::::::::::::

main.cpp

#include <iostream>     
#include "Test.h"  
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace FableGame;
 
const int MIN_PER_HR = 60;//每小时的分钟数

bool newcustomer(double x);
int main(int argc, const char * argv[])
{
	srand(time(0));//随机数种子
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue: ";
	int qs;//队列最大长度
	cin >> qs;
	

	cout << "Enter the number of simulation hours: ";
	int hours;//模拟的小时数
	cin >> hours;
	int cyclelimit = MIN_PER_HR * hours;//总分钟数限制

	Item temp;
	int lastturnaways = 0;//来了没处理就离开的人
	int lastcustomers = 0;//客户数
	int lastserved = 0;//已经服务过的客户数
	int lastsum_line = 0;//队列总长度
	int lastline_wait = 0;//总的等待时间
	double perhour = 1;//每小时接收的客人

	while (true)
	{       Queue line(qs);//队列应该放这里...
		double min_per_cust = MIN_PER_HR / perhour;
		int turnaways = 0;//来了没处理就离开的人
		int customers = 0;//客户数
		int served = 0;//已经服务过的客户数
		int sum_line = 0;//队列总长度
		int line_wait = 0;//总的等待时间
		int wait_time = 0;//正在处理业务时间
		for (int cycle = 0; cycle < cyclelimit; ++cycle)
		{
			if (newcustomer(min_per_cust))
			{
				//有客户来了
				if (line.isfull())
				{
					turnaways++;//队伍满了,离开
				}
				else
				{
					customers++; //增加客户
					temp.set(cycle);
					line.enqueue(temp);//加入队列
				}
			}
			if (wait_time <= 0 && !line.isempty())
			{
				line.dequeue(temp);//处理客户
				wait_time = temp.ptime();
				line_wait += cycle - temp.when();//等待时间
				served++;//服务的客户加1
			}
			if (wait_time > 0)
			{
				wait_time--;//每分钟减1
			}
			sum_line += line.queuecount();//这分钟正在等待的人数
		}
		if ((double)line_wait / served > 1)
		{
			break;
		}
		else
		{
			lastturnaways = turnaways;
			lastcustomers = customers;
			lastserved = served;
			lastsum_line = sum_line;
			lastline_wait = line_wait;
			perhour++;
		}
		
	} 
	
	if (lastcustomers > 0)
	{
		cout << "customers per hour: " << perhour << endl;
		cout << "customers accepted: " << lastcustomers << endl;
		cout << "customers served: " << lastserved << endl;
		cout << "turnsways: " << lastturnaways << endl;
		cout << "average queue size: ";
		cout.precision(2);
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout << (double)lastsum_line / cyclelimit << endl;
		cout << "average wait time: " << (double)lastline_wait / lastserved << " minutes\n";
	}
	else
	{
		cout << "No customers!\n";
	}
	cout << "Done!\n";

	return 0;
}

//判断客户是否到来
bool newcustomer(double x)
{
	return (rand() * x / RAND_MAX < 1);
} 
加大检测的总时长,可以得出更加平均的时间,大概19个左右吧.在队列总长度不变的情况下.


6.Heather银行想知道,如果再开一台ATM,情况如何。请对模拟进行修改,以包含两个队列。假设当第一台ATM前的排队人数少于第二台ATM时,客户将排在第一队,否则将排在第二队。然后再找出要使平均等候时间为1分钟,每小时到达的客户数应该为多少(注意,这是一个非线性问题,即将ATM数量加倍,并不能保证每小时处理客户数量也翻倍,并确保客户等候的时间少于1分钟)?

#include <iostream>     
#include "Test.h"  
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace FableGame;
 
const int MIN_PER_HR = 60;//每小时的分钟数

bool newcustomer(double x);
int main(int argc, const char * argv[])
{
	srand(time(0));//随机数种子
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximum size of queue: ";
	int qs;//队列最大长度
	cin >> qs;

	cout << "Enter the number of simulation hours: ";
	int hours;//模拟的小时数
	cin >> hours;
	int cyclelimit = MIN_PER_HR * hours;//总分钟数限制

	Item temp;
	int lastturnaways = 0;//来了没处理就离开的人
	int lastcustomers = 0;//客户数
	int lastserved = 0;//已经服务过的客户数
	int lastsum_line = 0;//队列总长度
	int lastline_wait = 0;//总的等待时间
	double perhour = 1;//每小时接收的客人

	while (true)
	{
		Queue line1(qs);
		Queue line2(qs);
		double min_per_cust = MIN_PER_HR / perhour;
		int turnaways = 0;//来了没处理就离开的人
		int customers = 0;//客户数
		int served = 0;//已经服务过的客户数
		int sum_line = 0;//队列总长度
		int line_wait = 0;//总的等待时间
		int wait_time1 = 0;//正在处理业务时间
		int wait_time2 = 0;//正在处理业务时间
		for (int cycle = 0; cycle < cyclelimit; ++cycle)
		{
			if (newcustomer(min_per_cust))
			{
				//有客户来了
				if (line1.isfull() && line2.isfull())
				{
					turnaways++;//队伍满了,离开
				}
				else
				{
					customers++; //增加客户
					temp.set(cycle);
					if (line1.queuecount() <= line2.queuecount())
					{
						line1.enqueue(temp);//加入队列1
					}
					else
					{
						line2.enqueue(temp);//加入队列2
					}
				}
			}
			if (wait_time1 <= 0 && !line1.isempty())
			{
				line1.dequeue(temp);//处理客户
				wait_time1 = temp.ptime();
				line_wait += cycle - temp.when();//等待时间
				served++;//服务的客户加1
			}
			if (wait_time1 > 0)
			{
				wait_time1--;//每分钟减1
			}
			if (wait_time2 <= 0 && !line2.isempty())
			{
				line2.dequeue(temp);//处理客户
				wait_time2 = temp.ptime();
				line_wait += cycle - temp.when();//等待时间
				served++;//服务的客户加1
			}
			if (wait_time2 > 0)
			{
				wait_time2--;//每分钟减1
			}
			sum_line += line1.queuecount();//这分钟正在等待的人数
			sum_line += line2.queuecount();//这分钟正在等待的人数
		}
		if (served > 0 && (double)line_wait / served > 1)
		{
			break;
		}
		else
		{
			lastturnaways = turnaways;
			lastcustomers = customers;
			lastserved = served;
			lastsum_line = sum_line;
			lastline_wait = line_wait;
			perhour++;
		}
		
	} 
	
	if (lastcustomers > 0)
	{
		cout << "customers per hour: " << perhour << endl;
		cout << "customers accepted: " << lastcustomers << endl;
		cout << "customers served: " << lastserved << endl;
		cout << "turnsways: " << lastturnaways << endl;
		cout << "average queue size: ";
		cout.precision(2);
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout << (double)lastsum_line / cyclelimit << endl;
		cout << "average wait time: " << (double)lastline_wait / lastserved << " minutes\n";
	}
	else
	{
		cout << "No customers!\n";
	}
	cout << "Done!\n";

	return 0;
}

//判断客户是否到来
bool newcustomer(double x)
{
	return (rand() * x / RAND_MAX < 1);
} 
只考虑了队列数不变的情况下.如果要考虑队列数,则更加复杂了.













转载于:https://www.cnblogs.com/fablegame/p/6430240.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值