C++ primer plus第六版第12章编程题答案(全)

1.
//头文件
#ifndef C__12_hpp
#define C__12_hpp
#include <cstring>
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 /* C__12_hpp */
//定义
#include "C++12.hpp"
#include <iostream>
Cow::Cow()
{
    name[0]='\0';
    hobby=nullptr;
    weight=0;
}
Cow::Cow(const char * num,const char * ho,double wt)
{
    strcpy(name,num);
    hobby=new char[20];
    strcpy(hobby,ho);
    weight=wt;
}
Cow::Cow(const Cow & c)
{
    strcpy(name,c.name);
    hobby=new char[20];
    strcpy(hobby,c.hobby);
    weight=c.weight;
}
Cow::~Cow()
{
    name[0]='\0';
    delete []hobby;
    weight=0;
    
}
Cow & Cow::operator=(const Cow & c)
{
    if(this==&c)
        return *this;
    delete []hobby;
    strcpy(name,c.name);
    hobby=new char[20];
    strcpy(hobby,c.hobby);
    weight=c.weight;
    return *this;
}
void Cow::ShowCow()const
{
    std::cout<<"名字:"<<name<<std::endl;
    std::cout<<"爱好:"<<hobby<<std::endl;
    std::cout<<"体重:"<<weight<<std::endl;
}
//主文件
#include <iostream>
#include "C++12.hpp"
int main() {
    Cow a("李佳琪","带货",50.0);
    Cow b=a;
    b.ShowCow();
    Cow c("周润发","表演",60);
    b=c;
    b.ShowCow();
    return 0;
}

2.
//头文件
#ifndef C__12_hpp
#define C__12_hpp

#include <iostream>
using std::ostream;
using std::istream;
class String
{
private:
    char * str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
public:
    
    String(const char * s);
    String();
    String (const String &);
    ~String();
    void stringlow();
    void stringup();
    int has(char c)const;
    friend  String  operator+(const String & s,const String & t);
    bool operator==(const String & s)const;
    String & operator=(const String &);
    String & operator=(const char *);
    friend std::ostream & operator<<(std::ostream & os,const String & s);
    friend std::istream & operator>>(std::istream & is,String & s);
};

#endif /* C__12_hpp */
//定义
#include "C++12.hpp"
#include <cstring>
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=nullptr;
       num_strings++;
}
String::String (const String & s)
{
    ++num_strings;
    len=s.len;
    str=new char[len+1];
    strcpy(str,s.str);
}
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;
}
bool String::operator==(const String & s)const
{
    return (strcmp(str,s.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;
}

void String::stringup()
{
    for(int i=0;i<len;++i)
        str[i]=toupper(str[i]);
   
}
void String::stringlow()
{
    for(int i=0;i<len;++i)
    str[i]=tolower(str[i]);
   
}
int String::has(char c)const
{
    int m=0;
    for(int i=0;i<len;++i)
        if(str[i]==c)
            ++m;
    return m;
}
 String operator+(const String & s,const String & t)
{
    String m;
    m.len=s.len+t.len;
    m.str=new char[m.len+1];
    strcat(m.str,s.str);
    strcat(m.str,t.str);
    return m;
}
//主文件
#include <iostream>
using namespace std;
#include "C++12.hpp"
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 for mixing hight: ";
    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.
//头文件
#ifndef C__12_3_hpp
#define C__12_3_hpp
#include <iostream>
class Stock
{
    char * company;
    int shares;
    double share_val;
    double total_val;
    void set_tot(){total_val=shares*share_val;};
public:
    Stock();
    Stock(const char* s,long n=0,double pr=0.0);
    ~Stock();
    Stock(const Stock & s);
    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 & s);
    const Stock & topval(const Stock & s)const;
    
};

#endif /* C__12_3_hpp */
//定义
#include "C++12_3.hpp"
#include <cstring>
Stock::Stock()
{
    company=nullptr;
    shares=0;
    share_val=0.0;
    set_tot();
}
Stock::Stock(const Stock & s)
{
    int len=strlen(s.company);
    company=new char [len+1];
    shares=s.shares;
    share_val=s.share_val;
    set_tot();
}
Stock::Stock(const char* s,long n,double pr)
{
    int len=strlen(s);
    company=new char[len+1];
    strcpy(company,s);
    if(n<0)
    {
        std::cout<<"Number of shares purchased can't be negative."
        <<company<<" shares set to 0.\n";
        shares=0;
    }
    else
        shares=n;
    share_val=pr;
    set_tot();
    
}
Stock::~Stock()
{
    delete []company;
}
void Stock::buy(long num,double price)
{
    if(num<0)
    {
        std::cout<<"Number of shares purchased can't be negative."
        <<"Transaction is aborted.\n";
    }
    else
    {
        shares+=num;
        share_val=price;
        set_tot();
    }
}
void Stock::sell(long num,double price)
{
    if(num>shares)
        std::cout<<"You can't sell more than you have!"
        <<"Transaction is aborted.\n";
    else if(num<0)
        std::cout<<"Number of shares sold can't be negative."
        <<"Transaction is aborted.\n";
    else
    {
        shares-=num;
        share_val=price;
        set_tot();
    }
}
void Stock::update(double price)
{
    share_val=price;
}
std::ostream& operator<<(std::ostream & os,const Stock & s)
{
    
    using std::ios_base;
    ios_base::fmtflags orig=
    os.setf(ios_base::fixed,ios_base::floatfield);
    std::streamsize prec=os.precision(3);
    os<<"Company: "<<s.company<<" Shares: "<<s.shares<<'\n';
    os<<" Share price: $"<<s.share_val;
    os.precision(2);
    os<<" Total Worth: $"<<s.total_val<<'\n';
    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;
}
//主文件
#include <iostream>
#include "C++12_3.hpp"
const int STKS = 4;
int main() {
    Stock stocks[STKS]{
        Stock("NanoSmart",12,20.0),
        Stock("Boffo Objects",100,1.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];
    const Stock * top=&stocks[0];
    for(st=1;st<STKS;st++)
        top=&top->topval(stocks[st]);
    std::cout<<"\nMost valuable holding:\n";
    std::cout<<*top;
    return 0;
}
4.
//头文件
#ifndef C__12_4_hpp
#define C__12_4_hpp

typedef unsigned long Item;
class Stack
{
private:
    enum{MAX = 10};
    Item *pitems;
    int size;//
    int top;
public:
    Stack(int n=MAX);//creat  n elements;
    Stack(const Stack &st);
    ~Stack();
    bool isempty()const;
    bool isfull()const;
    bool push(const Item & item);
    bool pop(Item & item);
    Stack & operator=(const Stack & st);
};

#endif /* C__12_4_hpp */
//定义
#include "C++12_4.hpp"
#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.top;++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==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)
        return false;
    else
    {
        item=pitems[--top];
        return true;
    }
}
Stack & Stack::operator=(const Stack & st)
{
    if(this==&st)
        return *this;
    pitems=new Item[st.size];
    for(int i=0;i<st.top;++i)
        pitems[i]=st.pitems[i];
    size=st.size;
    top=st.top;
    return *this;
}
//主文件
#include <iostream>
#include "C++12_4.hpp"
int main() {
    using namespace std;
    Stack s(3);
    cout<<"Enter a number:\n";
    Item m;
    while(!s.isfull()&&cin>>m)
    {
        s.push(m);
        cout<<m<<" added.\n";
    }
    Stack k;
    k=s;
    Item a;
    while(!k.isempty())
    {
        k.pop(a);
        cout<<a<<" popped.\n";
    }
    return 0;
}
5.
//头文件
#ifndef C__12_5_hpp
#define C__12_5_hpp

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 /* C__12_5_hpp */
//定义
#include "C++12_5.hpp"
#include <cstdlib>
Queue::Queue(int qs):qsize(qs)
{
    front=rear=nullptr;
    items=0;
}
Queue::~Queue()
{
    Node * temp;
    while(front!=NULL)
    {
        temp=front;
        front=front->next;
        delete temp;
    }
}
bool Queue::isempty()const
{
    return items==0;
}
bool Queue::isfull()const
{
    return items==qsize;
}
int Queue::queuecount()const
{
    return items;
}
bool Queue::enqueue(const Item & item)
{
    if(isfull())
        return false;
    Node * add=new Node;
    add->item=item;
    add->next=nullptr;
    items++;
    if(front==nullptr)//不能用if(isempty())替代。
        front=add;
    else
        rear->next=add;
    rear=add;
    return true;
}
bool Queue::dequeue(Item & item)
{
    if(front==nullptr)
        return false;
    item=front->item;
    Node * temp=front;
    front=front->next;
    delete temp;
    --items;
    if(items==0)
        rear=nullptr;
    return true;
}
void Customer::set(long when)
{
    processtime=rand()%3+1;
    arrive=when;
}
//主文件
#include <iostream>
#include "C++12_5.hpp"
#include <cstdlib>
#include <ctime>
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main() {
    using  std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
    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;
    long cyclelimit=hours*MIN_PER_HR;
    double perhour=1;
    double min_per_cust;
    while(1)
    {
    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;
    long line_wait=0;
    for(int i=0;i<cyclelimit;++i)
    {
        if(newcustomer(min_per_cust))
           {
            if(line.isfull())
            turnaways++;
            else
            {
                customers++;
                temp.set(i);
                line.enqueue(temp);
            }
           }
          if(wait_time<=0 && !line.isempty())
          {
              line.dequeue(temp);
              wait_time=temp.ptime();
              line_wait+=i-temp.when();
              served++;
          }
        if(wait_time>0)
            --wait_time;
        sum_line+=line.queuecount();
    }
    if((double)line_wait/served<1)
    {
        perhour++;
        continue;
    }
    else
        break;
    }
    cout<<"A "<<hours<<"-hour trial period, no more than "<<perhour-1<<" customers per hours.\n";
    return 0;
}
bool newcustomer(double x)
{
    return (std::rand()*x/RAND_MAX<1);
}
//结果是:每条队最多10人,200-1000小时,每小时最多人数大概是18人
6.
//头文件
#ifndef C__12_6_hpp
#define C__12_6_hpp
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 /* C__12_6_hpp */
//定义
#include "C++12_6.hpp"
#include <cstdlib>
Queue::Queue(int qs):qsize(qs)
{
    front=rear=nullptr;
    items=0;
}
Queue::~Queue()
{
    Node * temp;
    while(front!=NULL)
    {
        temp=front;
        front=front->next;
        delete temp;
    }
}
bool Queue::isempty()const
{
    return items==0;
}
bool Queue::isfull()const
{
    return items==qsize;
}
int Queue::queuecount()const
{
    return items;
}
bool Queue::enqueue(const Item & item)
{
    if(isfull())
        return false;
    Node * add=new Node;
    add->item=item;
    add->next=nullptr;
    items++;
    if(front==nullptr)//不能用if(isempty())替代。
        front=add;
    else
        rear->next=add;
    rear=add;
    return true;
}
bool Queue::dequeue(Item & item)
{
    if(front==nullptr)
        return false;
    item=front->item;
    Node * temp=front;
    front=front->next;
    delete temp;
    --items;
    if(items==0)
        rear=nullptr;
    return true;
}
void Customer::set(long when)
{
    processtime=rand()%3+1;
    arrive=when;
}
//主文件
#include <iostream>
#include "C++12_6.hpp"
#include <cstdlib>
#include <ctime>
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main() {
    using  std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
    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);
    Queue line1(qs);
    cout<<"Enter the number of simulation hours: ";
    int hours;
    cin>>hours;
    long cyclelimit=hours*MIN_PER_HR;
    double perhour=1;
    while(1)
    {
    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_time1=0;
    long line_wait=0;
    for(int i=0;i<cyclelimit;++i)
    {
        if(newcustomer(min_per_cust))
           {
            if(line.isfull()&&line1.isfull())
            turnaways++;
            else if(line.queuecount()>=line1.queuecount())
            {
                customers++;
                temp.set(i);
                line1.enqueue(temp);
            }
            else
            {
                customers++;
                temp.set(i);
                line.enqueue(temp);
            }
           }
          if(wait_time<=0 && !line.isempty())
          {
              line.dequeue(temp);
              wait_time=temp.ptime();
              line_wait+=i-temp.when();
              served++;
          }
        if(wait_time1<=0 && !line1.isempty())
        {
            line1.dequeue(temp);
            wait_time1=temp.ptime();
            line_wait+=i-temp.when();
            served++;
        }
        if(wait_time>0)
            --wait_time;
        if(wait_time1>0)
        --wait_time1;
    }
    if((double)line_wait/served<1)
    {
        perhour++;
        continue;
    }
    else
        break;
    }
    cout<<"two "<<hours<<"-hour trial period, no more than "<<perhour-1<<" customers per hours.\n";
    return 0;
}
bool newcustomer(double x)
{
    return (std::rand()*x/RAND_MAX<1);
}
//计算结果:每队最多10人,模拟200-1000小时,每小时最多51人左右;仅供参考,欢迎指正
/*完*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值