神秘博客

C++ Primer Plus [第六版]第12章编程练习题答案

1

#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

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

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

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

Cow::Cow(const Cow &c)
{
  strcpy_s(name, 20, c.name);
  hobby = new char[strlen(c.hobby) + 1];
  strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
  weight = c.weight;
}

Cow::~Cow()
{
  delete[] hobby;
}

Cow &Cow::operator=(const Cow &c)
{
  if (this == &c)
    return *this;
  strcpy_s(name, 20, c.name);
  delete[] hobby;
  hobby = new char[strlen(c.hobby) + 1];
  strcpy_s(hobby, strlen(c.hobby) + 1, c.hobby);
  weight = c.weight;

  return *this;
}

void Cow::ShowCow() const
{
  using std::cout;
  using std::endl;
  cout << "姓名: " << name << endl;
  cout << "爱好: " << hobby << endl;
  cout << "体重[kg]: " << weight << endl;
}
#include <iostream>
#include "cow.h"

int main()
{	
  using namespace std;
  Cow p1;
  Cow p2("神秘", "电脑", 55);
  p1 = p2;
  
  p1.ShowCow();
  p2.ShowCow();

  Cow p3 = p2;
  p3.ShowCow();
  
  system("pause");
  return 0;
}

2

#ifndef STRING_H_
#define STRING_H_
#include <iostream>
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();        
  int has(const char &s);
  void stringlow();
  void stringup();
  int length() const { return len; }  
  String & operator=(const String &);
  String & operator=(const char *);
  String operator+(const String &s);
  char & operator[](int i);
  const char & operator[](int i) const;
  friend String operator+(const char *st1, const String &s);
  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 std::ostream & operator<<(std::ostream & os, const String & st);
  friend std::istream & operator>>(std::istream & is, String & st);
  static int HowMany();

};

#endif
#include <cstring>   
#include <cctype>
#include "string.h"          
using std::cin;
using std::cout;

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];      
  strcpy_s(str, len + 1, 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_s(str, len + 1, st.str);
}

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

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

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

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

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

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

String String::operator+(const String &s)
{
  String temp;
  temp.str = new char[strlen(str) + strlen(s.str) + 1];
  temp.len = strlen(str) + strlen(s.str);
  strcpy_s(temp.str, temp.len + 1, str);
  strcat_s(temp.str, temp.len + 1, s.str);
  return temp;
}

char & String::operator[](int i)
{
  return str[i];
}


const char & String::operator[](int i) const
{
  return str[i];
}

String operator+(const char *st1, const String &s)
{
  String temp;
  temp.str = new char[strlen(st1) + strlen(s.str) + 1];
  temp.len = strlen(st1) + strlen(s.str);
  strcpy_s(temp.str, temp.len + 1, st1);
  strcat_s(temp.str, temp.len + 1, s.str);
  return temp;
}


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

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

std::istream & operator>>(std::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;
}
#include <iostream>
#include "string.h"

int main()
{
  using namespace std;
  String s1(" and I am a C++ student.");
  String s2 = "Please enter your name: ";
  String s3;
  cout << s2; //overload <<operator
  cin >> s3; //overload >>operator
  s2 = "My name is " + s3; //overload = , + operators
  cout << s2 << ".\n";
  s2 = s2 + s1;
  s2.stringup(); //converts string to uppercase
  cout << "The string\n" << s2 << "\ncontains " << s2.has('A') << " 'A' characters in it.\n";
  s1 = "red"; //String (const char *),
        //then String & operator= (const String&)
  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(); //converts string to lowercase
    for (int i = 0; i < 3; i++)
    {
      if (ans == rgb[i]) //overload == operator
      {
        cout << "That's right!\n";
        success = true;
        break;
      }
    }
    if (success)
      break;
    else
      cout << "Try again!\n";
  }
  cout << "Bye\n";

  system("pause");
  return 0;
}

3

#ifndef STOCK20_H_
#define STOCK20_H_
#include <string>
#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);
  void show()const;
  const Stock & topval(const Stock & s) const;
  friend std::ostream &operator<<(std::ostream &os, const Stock &s);
};

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

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


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

void Stock::show() const
{
  using std::cout;
  using std::ios_base;
  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;
  cout.precision(2);
  cout << "  Total Worth: $" << total_val << '\n';

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

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;
}
#include <iostream>
#include "stock.h"

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

    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;
  }
  
  system("pause");
  return 0;
}

4

#ifndef STACK_H_
#define STACK_H_

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

#endif
#include <iostream>
#include "stack.h"


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

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

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

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

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

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

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

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

void menu();

int main()
{
  using namespace std;
  int num;
  cout << "请输入栈的大小: ";
  cin >> num;
  Stack list(num);
  menu();
  int option;
  Item temp;
  while (cin >> option)
  {
    switch (option)
    {
    case 1:
      cout << "请输入你要添加的整数: ";
      cin >> temp;
      if (list.push(temp))
        cout << "添加完成\n";
      else
        cout << "栈已满...\n";
      break;
    case 2:
      if (list.pop(temp))
        cout << "弹出数据: " << temp << endl;
      else
        cout << "栈为空...\n";
      break;
    case 3:
      if (list.isempty())
        cout << "请先添加数据...\n";
      else
      {
        Stack *p1 = new Stack(list);
        cout << "复制成功, 弹出数据: \n";
        while (p1->pop(temp))
          cout << "弹出数据: " << temp << endl;
        cout << "弹出完成...\n";
        delete p1;
      }
      break;
    case 4:
      if (list.isempty())
        cout << "请先添加数据...\n";
      else
      {
        Stack p2;
        p2 = list;
        cout << "赋值成功, 弹出数据: \n";
        while (p2.pop(temp))
          cout << "弹出数据: " << temp << endl;
        cout << "弹出完成...\n";
      }
      break;
    default:
      cout << "请输入正确的选项: ";
      continue;
    }
    menu();
  }
  cout << "完成\n";

  system("pause");
  return 0;
}

void menu()
{
  using namespace std;
  cout << "**********栈管理**********\n";
  cout << "1. 添加数据 \t2. 弹出数据\n";
  cout << "3. 复制 \t4. 赋值\n";
  cout << "q. 退出\n";
  cout << "**************************\n";
}

5

这个自己随便试就行了,队列10,小时100,每小时17人。

6

这个到达自己随便试就行了,队列10,小时100,每小时45人左右。

#ifndef QUEUE_H_
#define QUEUE_H_

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);
  bool operator<(const Queue &st) const;
};

#endif
#include <iostream>
#include <cstdlib>
#include "queue.h"

Queue::Queue(int qs) : qsize(qs)
{
  front = rear = NULL;
  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 = NULL;
  items++;
  if (front == NULL)
    front = add;
  else
    rear->next = add;
  rear = add;
  return true;
}

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

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

bool Queue::operator<(const Queue &st) const
{
  return (items < st.items);
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"
const int MIN_PER_HR = 60;
const int Maxlen = 2;  
bool newcustomer(double x);

int main()
{
  using std::cin;
  using std::cout;
  using std::endl;
  using std::ios_base;
  std::srand(unsigned int(time(0)));

  cout << "案例研究:希瑟银行自动柜员机\n";
  cout << "输入队列的最大大小: ";
  int qs; //队列大小
  cin >> qs;
  Queue line[Maxlen]{ qs,qs };

  cout << "输入模拟小时数: ";
  int hours;  //模拟小时
  cin >> hours;
  long cyclelimit = MIN_PER_HR * hours; //模拟分钟

  cout << "输入每小时的平均客户数量: ";
  double perhour; //每小时客户数量
  cin >> perhour;
  double min_per_cust;  //平均几分钟来一个客户
  min_per_cust = MIN_PER_HR / perhour;

  Item temp[Maxlen];
  long turnaways = 0;  //拒绝人数
  long customers[Maxlen] = { 0,0 };  //加入人数
  long served[Maxlen] = { 0,0 };  //服务完人数
  long sum_line = 0; //队列总人数
  int wait_time[Maxlen] = { 0,0 };  //当前客户服务剩余时间
  long line_wait[Maxlen] = { 0,0 }; //客户到被服务的等待时间

  for (int cycle = 0; cycle < cyclelimit; cycle++)
  {
    if (newcustomer(min_per_cust))
    {
      if (line[0].isfull())
        turnaways++;
      else
      {
        if (line[0] < line[1])
        {
          customers[0]++;
          temp[0].set(cycle);
          line[0].enqueue(temp[0]);
        }
        else
        {
          customers[1]++;
          temp[1].set(cycle);
          line[1].enqueue(temp[1]);
        }
      }
    }
    if (wait_time[0] <= 0 && !line[0].isempty())
    {
      line[0].dequeue(temp[0]);
      wait_time[0] = temp[0].ptime();
      line_wait[0] += cycle - temp[0].when();
      served[0]++;
    }
    if (wait_time[0] > 0)
      wait_time[0]--;
    if (wait_time[1] <= 0 && !line[1].isempty())
    {
      line[1].dequeue(temp[1]);
      wait_time[1] = temp[1].ptime();
      line_wait[1] += cycle - temp[1].when();
      served[1]++;
    }
    if (wait_time[1] > 0)
      wait_time[1]--;
    sum_line += line[0].queuecount() + line[1].queuecount();

  }

  if (customers[0] > 0)
  {
    cout << "********************\n";
    cout << "ATM 1: \n";
    cout << "客户接受: " << customers[0] << endl;
    cout << "客户服务: " << served[0] << endl;
    cout.precision(2);
    cout.setf(ios_base::fixed, ios_base::floatfield);
    cout << "平均等待时间: ";
    cout << (double)line_wait[0] / served[0] << " 分钟" << endl;

    cout << "ATM 2: \n";
    cout << "客户接受: " << customers[1] << endl;
    cout << "客户服务: " << served[1] << endl;
    cout << "平均等待时间: ";
    cout << (double)line_wait[1] / served[1] << " 分钟" << endl;
    cout << "********************\n";
    cout << "平均队列大小: ";
    cout << (double)sum_line / cyclelimit << endl;
    cout << "总拒绝人数: " << turnaways << endl;
  }
  else
    cout << "没客户!\n";
  cout << "完成\n";

  system("pause");
  return 0;
}

bool newcustomer(double x)
{
  return (std::rand()*x / RAND_MAX < 1);
}

 

版权说明:
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

觉得文章有用就请我吃包辣条吧

微信扫一扫打赏