C++ Primer Plus(第六版)中文版编程练习答案

1

vect.h

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode {RECT, POL};
    // RECT for rectangular, POL for Polar modes
    private:
        double x;          // horizontal value
        double y;          // vertical value
        double mag;        // length of vector
        double ang;        // direction of vector in degrees
        Mode mode;         // RECT or POL
    // private methods for setting values
        void set_mag();
        void set_ang();
        void set_x();
        void set_y();
    public:
       Vector();
        Vector(double n1, double n2, Mode form = RECT);
        void reset(double n1, double n2, Mode form = RECT);
        ~Vector();
        double xval() const {return x;}       // report x value
        double yval() const {return y;}       // report y value
        double magval() const {return mag;}   // report magnitude
        double angval() const {return ang;}   // report angle
        void polar_mode();                    // set mode to POL
        void rect_mode();                     // set mode to RECT
    // operator overloading
        Vector operator+(const Vector & b) const;
        Vector operator-(const Vector & b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
    // friends
        friend Vector operator*(double n, const Vector & a);
        friend std::ostream & operator<<(std::ostream & os, const Vector & v);

        operator double() const { return mag; } //转换函数
    };

}   // end namespace VECTOR
#endif

exercise01_vect.cpp

// vect.cpp -- methods for the Vector class
#include <cmath>
#include "vect.h"   // includes <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;

namespace VECTOR
{
    // compute degrees in one radian
    const double Rad_to_deg = 45.0 / atan(1.0);
    // should be about 57.2957795130823

    // private methods
    // calculates magnitude from x and y
    void Vector::set_mag()
    {
        mag = sqrt(x * x + y * y);
    }

    void Vector::set_ang()
    {
        if (x == 0.0 && y == 0.0)
            ang = 0.0;
        else
            ang = atan2(y, x);
    }

    // set x from polar coordinate
    void Vector::set_x()
    {
        x = mag * cos(ang);
    }

    // set y from polar coordinate
    void Vector::set_y()
    {
        y = mag * sin(ang);
    }

    // public methods
    Vector::Vector()             // default constructor
    {
        x = y = mag = ang = 0.0;
        mode = RECT;
    }

    // construct vector from rectangular coordinates if form is r
    // (the default) or else from polar coordinates if form is p
    Vector::Vector(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }

    // reset vector from rectangular coordinates if form is
    // RECT (the default) or else from polar coordinates if
    // form is POL
    void Vector:: reset(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }

    Vector::~Vector()    // destructor
    {
    }

    void Vector::polar_mode()    // set to polar mode
    {
        mode = POL;
    }

    void Vector::rect_mode()     // set to rectangular mode
    {
        mode = RECT;
    }

    // operator overloading
    // add two Vectors
    Vector Vector::operator+(const Vector & b) const
    {
        return Vector(x + b.x, y + b.y);
    }

    // subtract Vector b from a
    Vector Vector::operator-(const Vector & b) const
    {
        return Vector(x - b.x, y - b.y);
    }

    // reverse sign of Vector
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }

    // multiply vector by n
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }

    // friend methods
    // multiply n by Vector a
    Vector operator*(double n, const Vector & a)
    {
        return a * n;
    }

    // display rectangular coordinates if mode is RECT,
    // else display polar coordinates if mode is POL
    std::ostream & operator<<(std::ostream & os, const Vector & v)
    {
        if (v.mode == Vector::RECT)
             os << "(x,y) = (" << v.x << ", " << v.y << ")";
        else if (v.mode == Vector::POL)
        {
             os << "(m,a) = (" << v.mag << ", "
                 << v.ang * Rad_to_deg << ")";
        }
        else
             os << "Vector object mode is invalid";
        return os; 
    }

}  // end namespace VECTOR

exercise01_randwalk.cpp

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "vect.h"
#include<fstream>

int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;

    //写入文件
    ofstream ofs("randwalk.txt", ios::out);

    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        else
            ofs << "Target Distance: " << target 
            << ", Step Size: " << dstep << endl;

        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
            ofs << steps << ":(x,y) = (" << result.xval() << "," 
                << result.yval() << ")" << endl;
        }
        cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        cout << result << endl;
        ofs << "After " << steps << " steps, the subject "
            "has the following location:\n";
        //重载了 “<<”,可以直接按照格式写到文件中,而不用写成下边的形式
        ofs << result << endl;
        /*ofs << "(x,y) = (" << result.xval() << ","
            << result.yval() << ")" << endl;*/

        result.polar_mode();
        cout << " or\n" << result << endl;
        cout << "Average outward distance per step = "
            << result.magval()/steps << endl;
        //重载了 “<<”,可以直接按照格式写到文件中,而不用写成下边的形式
        ofs << " or\n" << result << endl;  
        /*ofs << " or\n" << "(m,a) = (" << result.magval() << ","
            << result.angval() << ")" << endl;*/
        ofs << "Average outward distance per step = "
            << result.magval() / steps << endl;

        steps = 0;
        result.reset(0.0, 0.0);
        cout << "Enter target distance (q to quit): ";
        ofs << endl;
    }
    cout << "Bye!\n";

    ofs.close();
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

2

vect2.h

// vect2.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode {RECT, POL};
    // RECT for rectangular, POL for Polar modes
    private:
        double x;          // horizontal value
        double y;          // vertical value
        Mode mode;         // RECT or POL

    // private methods for setting values
        void set_x(double mag, double ang);
        void set_y(double mag, double ang);

    public:
       Vector();
        Vector(double n1, double n2, Mode form = RECT);
        void reset(double n1, double n2, Mode form = RECT);
        ~Vector();

        double xval() const {return x;}       // report x value
        double yval() const {return y;}       // report y value
        double magval() const;   // report magnitude
        double angval() const;   // report angle

        void polar_mode();                    // set mode to POL
        void rect_mode();                     // set mode to RECT
    // operator overloading
        Vector operator+(const Vector & b) const;
        Vector operator-(const Vector & b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
    // friends
        friend Vector operator*(double n, const Vector & a);
        friend std::ostream & operator<<(std::ostream & os, const Vector & v);
    };

}   // end namespace VECTOR
#endif

exercise02_vect2.cpp

// vect2.cpp -- methods for the Vector class
#include <cmath>
#include "vect2.h"   // includes <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;

namespace VECTOR
{
    // compute degrees in one radian
    const double Rad_to_deg = 45.0 / atan(1.0);
    // should be about 57.2957795130823

    // private methods
    // set x from polar coordinate
    void Vector::set_x(double mag, double ang)
    {
        x = mag * cos(ang);
    }

    // set y from polar coordinate
    void Vector::set_y(double mag, double ang)
    {
        y = mag * sin(ang);
    }

    // report magnitude
    double Vector::magval() const
    {
        return sqrt(x * x + y * y);
    }

    // report angle
    double Vector::angval() const
    {
        if (x == 0.0 && y == 0.0)
            return 0.0;
        else
            return atan2(y, x);
    }

    // public methods
    Vector::Vector()             // default constructor
    {
        x = y = 0.0;
        mode = RECT;
    }

    // construct vector from rectangular coordinates if form is r
    // (the default) or else from polar coordinates if form is p
    Vector::Vector(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             magval();
             angval();
        }
        else if (form == POL)
        {
            double mag, ang;
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x(mag, ang);
             set_y(mag, ang);
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = 0.0;
             mode = RECT;
        }
    }

    // reset vector from rectangular coordinates if form is
    // RECT (the default) or else from polar coordinates if
    // form is POL
    void Vector:: reset(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             magval();
             angval();
        }
        else if (form == POL)
        {
            double mag, ang;
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x(mag, ang);
             set_y(mag, ang);
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = 0.0;
             mode = RECT;
        }
    }

    Vector::~Vector()    // destructor
    {
    }

    void Vector::polar_mode()    // set to polar mode
    {
        mode = POL;
    }

    void Vector::rect_mode()     // set to rectangular mode
    {
        mode = RECT;
    }

    // operator overloading
    // add two Vectors
    Vector Vector::operator+(const Vector & b) const
    {
        return Vector(x + b.x, y + b.y);
    }

    // subtract Vector b from a
    Vector Vector::operator-(const Vector & b) const
    {
        return Vector(x - b.x, y - b.y);
    }

    // reverse sign of Vector
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }

    // multiply vector by n
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }

    // friend methods
    // multiply n by Vector a
    Vector operator*(double n, const Vector & a)
    {
        return a * n;
    }

    // display rectangular coordinates if mode is RECT,
    // else display polar coordinates if mode is POL
    std::ostream & operator<<(std::ostream & os, const Vector & v)
    {
        if (v.mode == Vector::RECT)
             os << "(x,y) = (" << v.x << ", " << v.y << ")";
        else if (v.mode == Vector::POL)
        {
             os << "(m,a) = (" << v.magval() << ", "
                 << v.angval() * Rad_to_deg << ")";
        }
        else
             os << "Vector object mode is invalid";
        return os; 
    }

}  // end namespace VECTOR

exercise02_randwalk2.cpp

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "vect2.h"
#include<fstream>

int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;

    //写入文件
    ofstream ofs("randwalk2.txt", ios::out);

    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        else
            ofs << "Target Distance: " << target 
            << ", Step Size: " << dstep << endl;

        while (result.magval() < target)
        {
            direction = rand() % 360;
            step.reset(dstep, direction, Vector::POL);
            result = result + step;
            steps++;
            ofs << steps << ":(x,y) = (" << result.xval() << "," 
                << result.yval() << ")" << endl;
        }
        cout << "After " << steps << " steps, the subject "
            "has the following location:\n";
        cout << result << endl;
        ofs << "After " << steps << " steps, the subject "
            "has the following location:\n";
        //重载了 “<<”,可以直接按照格式写到文件中,而不用写成下边的形式
        ofs << result << endl;

        result.polar_mode();
        cout << " or\n" << result << endl;
        cout << "Average outward distance per step = "
            << result.magval()/steps << endl;
        //重载了 “<<”,可以直接按照格式写到文件中,而不用写成下边的形式
        ofs << " or\n" << result << endl;  
        ofs << "Average outward distance per step = "
            << result.magval() / steps << endl;

        steps = 0;
        result.reset(0.0, 0.0);
        cout << "Enter target distance (q to quit): ";
        ofs << endl;
    }
    cout << "Bye!\n";

    ofs.close();

/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

3

vect.h

// vect.h -- Vector class with <<, mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
    class Vector
    {
    public:
        enum Mode {RECT, POL};
    // RECT for rectangular, POL for Polar modes
    private:
        double x;          // horizontal value
        double y;          // vertical value
        double mag;        // length of vector
        double ang;        // direction of vector in degrees
        Mode mode;         // RECT or POL
    // private methods for setting values
        void set_mag();
        void set_ang();
        void set_x();
        void set_y();
    public:
       Vector();
        Vector(double n1, double n2, Mode form = RECT);
        void reset(double n1, double n2, Mode form = RECT);
        ~Vector();
        double xval() const {return x;}       // report x value
        double yval() const {return y;}       // report y value
        double magval() const {return mag;}   // report magnitude
        double angval() const {return ang;}   // report angle
        void polar_mode();                    // set mode to POL
        void rect_mode();                     // set mode to RECT
    // operator overloading
        Vector operator+(const Vector & b) const;
        Vector operator-(const Vector & b) const;
        Vector operator-() const;
        Vector operator*(double n) const;
    // friends
        friend Vector operator*(double n, const Vector & a);
        friend std::ostream & operator<<(std::ostream & os, const Vector & v);

        operator double() const { return mag; } //转换函数
    };

}   // end namespace VECTOR
#endif

exercise03_vect3.cpp

// vect.cpp -- methods for the Vector class
#include <cmath>
#include "vect.h"   // includes <iostream>
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;

namespace VECTOR
{
    // compute degrees in one radian
    const double Rad_to_deg = 45.0 / atan(1.0);
    // should be about 57.2957795130823

    // private methods
    // calculates magnitude from x and y
    void Vector::set_mag()
    {
        mag = sqrt(x * x + y * y);
    }

    void Vector::set_ang()
    {
        if (x == 0.0 && y == 0.0)
            ang = 0.0;
        else
            ang = atan2(y, x);
    }

    // set x from polar coordinate
    void Vector::set_x()
    {
        x = mag * cos(ang);
    }

    // set y from polar coordinate
    void Vector::set_y()
    {
        y = mag * sin(ang);
    }

    // public methods
    Vector::Vector()             // default constructor
    {
        x = y = mag = ang = 0.0;
        mode = RECT;
    }

    // construct vector from rectangular coordinates if form is r
    // (the default) or else from polar coordinates if form is p
    Vector::Vector(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }

    // reset vector from rectangular coordinates if form is
    // RECT (the default) or else from polar coordinates if
    // form is POL
    void Vector:: reset(double n1, double n2, Mode form)
    {
        mode = form;
        if (form == RECT)
         {
             x = n1;
             y = n2;
             set_mag();
             set_ang();
        }
        else if (form == POL)
        {
             mag = n1;
             ang = n2 / Rad_to_deg;
             set_x();
             set_y();
        }
        else
        {
             cout << "Incorrect 3rd argument to Vector() -- ";
             cout << "vector set to 0\n";
             x = y = mag = ang = 0.0;
             mode = RECT;
        }
    }

    Vector::~Vector()    // destructor
    {
    }

    void Vector::polar_mode()    // set to polar mode
    {
        mode = POL;
    }

    void Vector::rect_mode()     // set to rectangular mode
    {
        mode = RECT;
    }

    // operator overloading
    // add two Vectors
    Vector Vector::operator+(const Vector & b) const
    {
        return Vector(x + b.x, y + b.y);
    }

    // subtract Vector b from a
    Vector Vector::operator-(const Vector & b) const
    {
        return Vector(x - b.x, y - b.y);
    }

    // reverse sign of Vector
    Vector Vector::operator-() const
    {
        return Vector(-x, -y);
    }

    // multiply vector by n
    Vector Vector::operator*(double n) const
    {
        return Vector(n * x, n * y);
    }

    // friend methods
    // multiply n by Vector a
    Vector operator*(double n, const Vector & a)
    {
        return a * n;
    }

    // display rectangular coordinates if mode is RECT,
    // else display polar coordinates if mode is POL
    std::ostream & operator<<(std::ostream & os, const Vector & v)
    {
        if (v.mode == Vector::RECT)
             os << "(x,y) = (" << v.x << ", " << v.y << ")";
        else if (v.mode == Vector::POL)
        {
             os << "(m,a) = (" << v.mag << ", "
                 << v.ang * Rad_to_deg << ")";
        }
        else
             os << "Vector object mode is invalid";
        return os; 
    }

}  // end namespace VECTOR

exercise03_randwalk3.cpp

// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>      // rand(), srand() prototypes
#include <ctime>        // time() prototype
#include "vect.h"
#include<fstream>

int main()
{
    using namespace std;
    using VECTOR::Vector;
    srand(time(0));     // seed random-number generator
    double direction;
    Vector step;
    Vector result(0.0, 0.0);
    unsigned long steps = 0;
    double target;
    double dstep;

    int totalstep = 0;
    int minstep = INT_MAX - 1;
    int maxstep = 0;
    int n;

    //写入文件
    ofstream ofs("randwalk3.txt", ios::out);
    
    cout << "Enter target distance (q to quit): ";
    while (cin >> target)
    {
        cout << "Enter step length: ";
        if (!(cin >> dstep))
            break;
        else
            ofs << "Target Distance: " << target 
            << ", Step Size: " << dstep << endl;

        cout << "Enter times of the test: ";
        cin >> n;
        ofs << "Times of the test: " << n << endl;

        totalstep = 0;

        for (int i = 0; i < n; i++)
        {
            while (result.magval() < target)
            {
                direction = rand() % 360;
                step.reset(dstep, direction, Vector::POL);
                result = result + step;
                steps++;
            }

            totalstep += steps;
            minstep = minstep < steps ? minstep : steps;
            maxstep = maxstep > steps ? maxstep : steps;

            steps = 0;
            result.reset(0.0, 0.0);
        }
        cout << "totalstep: " << totalstep << "\n"
            << "maxstep: " << maxstep << "\n"
            << "minstep: " << minstep << "\n"
            << "average: " << double(totalstep) / double(n) << endl;
        ofs << "totalstep: " << totalstep << "\t"
            << "maxstep: " << maxstep << "\t"
            << "minstep: " << minstep << "\t"
            << "average: " << double(totalstep) / double(n) << endl;
        ofs << endl;

        cout << "Enter target distance (q to quit): ";
    }
    
    cout << "Bye!\n";

    ofs.close();
/* keep window open
    cin.clear();
    while (cin.get() != '\n')
        continue;
    cin.get();
*/
    return 0; 
}

4

mytime4.h

// mytime4.h -- Time class with friends
#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>

class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m = 0);
    void AddMin(int m);
    void AddHr(int h);
    void Reset(int h = 0, int m = 0);

    friend Time operator+(const Time& t1, const Time t2);
    friend Time operator-(const Time& t1, const Time t2);
    friend Time operator*(const Time& t, double n);
    friend Time operator*(double m, const Time& t)
        { return t * m; }   // inline definition
    friend std::ostream & operator<<(std::ostream & os, const Time & t);

};
#endif

exercise04_mytime4.cpp

// mytime3.cpp  -- implementing Time methods
#include "mytime4.h"

Time::Time()
{
    hours = minutes = 0;
}

Time::Time(int h, int m )
{
    hours = h;
    minutes = m;
}

void Time::AddMin(int m)
{
    minutes += m;
    hours += minutes / 60;
    minutes %= 60;
}

void Time::AddHr(int h)
{
    hours += h;
}

void Time::Reset(int h, int m)
{
    hours = h;
    minutes = m;
}

Time operator+(const Time& t1, const Time t2)
{
    Time sum;
    sum.minutes = t1.minutes + t2.minutes;
    sum.hours = t1.hours + t2.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}

Time operator-(const Time& t1, const Time t2)
{
    Time diff;
    int tot1, tot2;
    tot1 = t1.minutes + 60 * t1.hours;
    tot2 = t2.minutes + 60 * t2.hours;
    diff.minutes = (tot2 - tot1) % 60;
    diff.hours = (tot2 - tot1) / 60;
    return diff;
}

Time operator*(const Time& t, double mult)
{
    Time result;
    long totalminutes = t.hours * mult * 60 + t.minutes * mult;
    result.hours = totalminutes / 60;
    result.minutes = totalminutes % 60;
    return result;
}

std::ostream & operator<<(std::ostream & os, const Time & t)
{
    os << t.hours << " hours, " << t.minutes << " minutes";
    return os; 
}

exercise04_usetime4.cpp

//usetime3.cpp -- using the fourth draft of the Time class
// compile usetime3.cpp and mytime3.cpp together
#include <iostream>
#include "mytime4.h"

int main()
{
    using std::cout;
    using std::endl;
    Time aida(3, 35);
    Time tosca(2, 48);
    Time temp;

    cout << "Aida and Tosca:\n";
    cout << aida<<"; " << tosca << endl;
    temp = aida + tosca;     // operator+()
    cout << "Aida + Tosca: " << temp << endl;
    temp = aida* 1.17;  // member operator*()
    cout << "Aida * 1.17: " << temp << endl;
    cout << "10.0 * Tosca: " << 10.0 * tosca << endl;
	// std::cin.get();
    return 0; 
}

5

stonewt2.h

// stonewt2.h -- definition for the Stonewt class
#include<iostream>
#ifndef STONEWT_H_
#define STONEWT_H_

class Stonewt
{
public:
    enum Mode { STONE, INTPOUND, FLOATPOUND };

private:
    enum {Lbs_per_stn = 14};      // pounds per stone
    int stone;                    // whole stones
    double pds_left;              // fractional pounds
    double pounds;                // entire weight in pounds
    Mode mode1;
    int mode2;

public:
    Stonewt(double lbs);          // constructor for double pounds
    Stonewt(int stn, double lbs); // constructor for stone, lbs
    Stonewt();                    // default constructor
    ~Stonewt();

    void setmode(int a);
    Stonewt operator+(const Stonewt& s) const;
    Stonewt operator-(const Stonewt& s) const;
    Stonewt operator*(double d) const;
    friend Stonewt operator*(double d, const Stonewt& s)
    {  return s * d; }
    friend std::ostream& operator<<(std::ostream& os, const Stonewt& s);
};
#endif

exercise05_stonewt2.cpp

// stonewt.cpp -- Stonewt methods
#include <iostream>
using std::cout;
#include "stonewt2.h"

// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
    stone = int (lbs) / Lbs_per_stn;    // integer division
    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
    mode2 = 3;
}

// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
    mode2 = 3;
}

Stonewt::Stonewt()          // default constructor, wt = 0
{
    stone = pounds = pds_left = 0;
    mode2 = 3;
}

Stonewt::~Stonewt()         // destructor
{
}

void Stonewt::setmode(int a)
{
    mode2 = a;
}

Stonewt Stonewt::operator+(const Stonewt& s) const
{
    Stonewt ret;
    ret.pounds = pounds + s.pounds;
    ret.stone += ret.pounds / Lbs_per_stn;
    ret.pds_left = int(ret.pounds) % Lbs_per_stn;
    return ret;
}

Stonewt Stonewt::operator-(const Stonewt& s) const
{
    double p;
    p = pounds - s.pounds;
    Stonewt ret(p);
    /*ret.stone = p / Lbs_per_stn;
    ret.pounds = int(p) % Lbs_per_stn;*/
    return ret;

    /*Stonewt ret;
    double po1, po2;
    po1 = pounds + stone * Lbs_per_stn;
    po2 = s.pounds + s.stone * Lbs_per_stn;
    ret.stone = (po1 - po2) / Lbs_per_stn;
    ret.pounds = int(po1 - po2) % Lbs_per_stn;
    return ret;*/
}

Stonewt Stonewt::operator*(double d) const
{
    double total;
    total = pounds * d;
    Stonewt ret(total);
    /*ret.stone = total / Lbs_per_stn;
    ret.pounds = int(total) % Lbs_per_stn;*/
    return ret;
}

std::ostream& operator<<(std::ostream& os, const Stonewt& s)
{
    if (s.mode2 == 1)
        os << "Stone = " << s.stone << std::endl;
    else if (s.mode2 == 2)
    {
        os << "Int Pounds = " << s.pounds << std::endl;
    }
    else if (s.mode2 == 3)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds\n";
    }
    else
         os << "Vector object mode is invalid";
    return os; 
}

exercise05_stone2.cpp

// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
#include "stonewt2.h"

int main()
{
    Stonewt incognito = 275; // uses constructor to initialize
    int state;
    string st[3] = { "Stone","Int pounds","Float pounds" };

    for (int i = 0; i < 3; i++)
    {
        incognito.setmode(i + 1);
        cout << "incognito(" << st[i] << "): " << incognito;
    }

    Stonewt wolfe(285.7);    // same as Stonewt wolfe = 285.7;
    cout << wolfe;
    Stonewt taft(21, 8);
    cout << taft;
    cout << "--------------------\n";

    Stonewt st1, st2, st3, st4;
    st1 = wolfe + taft;
    cout << st1;
    st1.setmode(1);
    cout << st1;
    st1.setmode(2);
    cout << st1;
    st1.setmode(3);
    cout << st1;
    cout << "--------------------\n";

    st4 = taft - wolfe;
    cout << st4;
    st4.setmode(1);
    cout << st4;
    st4.setmode(2);
    cout << st4;
    st4.setmode(3);
    cout << st4;
    cout << "--------------------\n";

    st2 = st1 * 2.5;
    cout << st2;
    st3 = 2.5 * st1;
    cout << st3;

    // std::cin.get();
    return 0;
}

6

stonewt3.h

// stonewt3.h -- definition for the Stonewt class
#include<iostream>
#ifndef STONEWT_H_
#define STONEWT_H_

class Stonewt
{
public:
    enum Mode { STONE, INTPOUND, FLOATPOUND };

private:
    enum {Lbs_per_stn = 14};      // pounds per stone
    int stone;                    // whole stones
    double pds_left;              // fractional pounds
    double pounds;                // entire weight in pounds
    Mode mode1;
    int mode2;

public:
    Stonewt(double lbs);          // constructor for double pounds
    Stonewt(int stn, double lbs); // constructor for stone, lbs
    Stonewt();                    // default constructor
    ~Stonewt();

    void setmode(int a);
    Stonewt operator+(const Stonewt& s) const;
    Stonewt operator-(const Stonewt& s) const;
    Stonewt operator*(double d) const;
    friend Stonewt operator*(double d, const Stonewt& s)
    {  return s * d; }
    friend std::ostream& operator<<(std::ostream& os, const Stonewt& s);

    friend bool operator>(const Stonewt& s1, const Stonewt& s2);
    friend bool operator<(const Stonewt& s1, const Stonewt& s2);
    friend bool operator>=(const Stonewt& s1, const Stonewt& s2);
    friend bool operator<=(const Stonewt& s1, const Stonewt& s2);
    friend bool operator==(const Stonewt& s1, const Stonewt& s2);
    friend bool operator!=(const Stonewt& s1, const Stonewt& s2);
};
#endif

exercise06_stonewt3.cpp

// stonewt.cpp -- Stonewt methods
#include <iostream>
using std::cout;
#include "stonewt3.h"

// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
    stone = int (lbs) / Lbs_per_stn;    // integer division
    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
    pounds = lbs;
    mode2 = 3;
}

// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
    stone = stn;
    pds_left = lbs;
    pounds =  stn * Lbs_per_stn +lbs;
    mode2 = 3;
}

Stonewt::Stonewt()          // default constructor, wt = 0
{
    stone = pounds = pds_left = 0;
    mode2 = 3;
}

Stonewt::~Stonewt()         // destructor
{
}

void Stonewt::setmode(int a)
{
    mode2 = a;
}

Stonewt Stonewt::operator+(const Stonewt& s) const
{
    Stonewt ret;
    ret.pounds = pounds + s.pounds;
    ret.stone += ret.pounds / Lbs_per_stn;
    ret.pds_left = int(ret.pounds) % Lbs_per_stn;
    return ret;
}

Stonewt Stonewt::operator-(const Stonewt& s) const
{
    double p;
    p = pounds - s.pounds;
    Stonewt ret(p);
    /*ret.stone = p / Lbs_per_stn;
    ret.pounds = int(p) % Lbs_per_stn;*/
    return ret;

    /*Stonewt ret;
    double po1, po2;
    po1 = pounds + stone * Lbs_per_stn;
    po2 = s.pounds + s.stone * Lbs_per_stn;
    ret.stone = (po1 - po2) / Lbs_per_stn;
    ret.pounds = int(po1 - po2) % Lbs_per_stn;
    return ret;*/
}

Stonewt Stonewt::operator*(double d) const
{
    double total;
    total = pounds * d;
    Stonewt ret(total);
    /*ret.stone = total / Lbs_per_stn;
    ret.pounds = int(total) % Lbs_per_stn;*/
    return ret;
}

std::ostream& operator<<(std::ostream& os, const Stonewt& s)
{
    if (s.mode2 == 1)
        os << "Stone = " << s.stone << std::endl;
    else if (s.mode2 == 2)
    {
        os << "Int Pounds = " << s.pounds << std::endl;
    }
    else if (s.mode2 == 3)
    {
        os << s.stone << " stone, " << s.pds_left << " pounds\n";
    }
    else
         os << "Vector object mode is invalid";
    return os; 
}


bool operator>(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds > s2.pounds)
        return true;
    else
        return false;
}

bool operator<(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds < s2.pounds)
        return true;
    else
        return false;
}

bool operator>=(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds >= s2.pounds)
        return true;
    else
        return false;
}

bool operator<=(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds <= s2.pounds)
        return true;
    else
        return false;
}

bool operator==(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds == s2.pounds)
        return true;
    else
        return false;
}

bool operator!=(const Stonewt& s1, const Stonewt& s2)
{
    if (s1.pounds != s2.pounds)
        return true;
    else
        return false;
}

exercise06_stone3.cpp

// stone.cpp -- user-defined conversions
// compile with stonewt.cpp
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
#include "stonewt3.h"

int main()
{
    Stonewt st[6] = { {60},{160.6},{80,10.6} };
    Stonewt stcom(11,0);
    Stonewt stmin = INT_MAX - 1, stmax = 0;
    int greater11 = 0;

    for (int i = 3; i < 6; i++)
    {
        double pound;
        cout << "Enter " << i + 1 << "th member: ";
        cin >> pound;
        st[i] = pound;
    }
    cout << "Done!\n";
    cout << "The members of Stonewt st are:\n";
    for (int i = 0; i < 6; i++)
    {
        cout << st[i];
        if (st[i] < stmin)
            stmin = st[i];
        if (st[i] > stmax)
            stmax = st[i];
        if (st[i] >= stcom)
            greater11++;
    }
    cout << "----------------\n";
    cout << "Min member: " << stmin << "Max member: " << stmax
        << "The number of members >= 11 stone is: " 
        << greater11 << endl;

    // std::cin.get();
    return 0;
}

7

complex0.h

#pragma once
#include<iostream>
using namespace std;

class complex
{
private:
	double real;
	double imaginary;

public:
	complex();
	complex(double a, double b);
	
	friend complex operator+(const complex& c1, const complex& c2);
	friend complex operator-(const complex& c1, const complex& c2);
	friend complex operator*(const complex& c1, const complex& c2);
	friend complex operator*(double d,const complex &c);
	friend complex operator*(const complex& c, double d)
	{ return d * c; }
	friend complex operator~(complex& c);

	friend ostream& operator<<(ostream& os, const complex& c);
	friend istream& operator>>(istream& is, complex& c);
};

exercise07_complex0.cpp

#include<iostream>
#include"complex0.h"
using namespace std;

complex::complex()
{
	real = 0;
	imaginary = 0;
}
complex::complex(double a, double b)
{
	real = a;
	imaginary = b;
}

complex operator+(const complex& c1, const complex& c2)
{
	return complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

complex operator-(const complex& c1, const complex& c2)
{
	return complex(c1.real - c2.real, c1.imaginary - c2.imaginary);
}

complex operator*(const complex& c1, const complex& c2)
{
	return complex(c1.real * c2.real - c1.imaginary * c2.imaginary,
		c1.real * c2.imaginary + c1.imaginary * c2.real);
}

complex operator*(double d, const complex& c)
{
	return complex(d * c.real, d * c.imaginary);
}

complex operator~(complex& c)
{
	return complex(c.real, -c.imaginary);
}

ostream& operator<<(ostream& os, const complex& c)
{
	os << "(" << c.real << "," << c.imaginary << "i)" << endl;
	return os;
}

istream& operator>>(istream& is, complex& c)
{
	cout << "real: ";
	is >> c.real;
	if (!is)
		return is;
	cout << "imaginary: ";
	is >> c.imaginary;

	return is;
}

exercise07.cpp

#include<iostream>
#include"complex0.h"
using namespace std;

int main()
{
	complex c1;
	cout << "c1: " << c1;
	complex c2(3, 4);
	cout << "c2: " << c2;
	cout << "------------------\n";

	complex a(3.0, 4.0);
	complex c;
	cout << "Enter a complex number (q to quit):\n";
	while (cin >> c)
	{
		cout << "c is " << c;
		cout << "complex conjugate is " << ~c;
		cout << "a is " << a;
		cout << "a + c is " << a + c;
		cout << "a - c is " << a - c;
		cout << "a * c is " << a * c;
		cout << "2 * c is " << 2 * c;
		cout << "Enter a complex number (q to quit): \n";
	}
	cout << "Done!\n";

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值