第八章
8.12(龟兔赛跑模拟)
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
const int RACE_END = 70;
void moveTortoise(int* const);
void moveHare(int* const);
void printCurrentPositions(const int* const, const int* const);
int main()
{
int tortoise = 1;
int hare = 1;
int timer = 0;
srand(time(0));
cout << "ON YOUR MARK, GET SET\nBANG !!!!"
<< "\nAND THEY'RE OFF !!!!\n";
while (tortoise != RACE_END && hare != RACE_END)
{
moveTortoise(&tortoise);
moveHare(&hare);
printCurrentPositions(&tortoise, &hare);
timer++;
}
if (tortoise >= hare)
cout << "\nTORTOISE WINS!!! YAY!!!\n";
else
cout << "Hare wins. Yuch.\n";
cout << "TIME ELAPSED = " << timer << " seconds" << endl;
}
void moveTortoise(int* const turtlePtr)
{
int x = 1 + rand() % 10;
if (x >= 1 && x <= 5)
*turtlePtr += 3;
else if (x == 6 || x == 7)
*turtlePtr -= 6;
else
++(*turtlePtr);
if (*turtlePtr < 1)
*turtlePtr = 1;
else if (*turtlePtr > RACE_END)
*turtlePtr = RACE_END;
}
void moveHare(int* const rabbitPtr)
{
int y = 1 + rand() % 10;
if (y == 3 || y == 4)
*rabbitPtr += 9;
else if (y == 5)
*rabbitPtr -= 12;
else if (y >= 6 && y <= 8)
++(*rabbitPtr);
else if (y > 8)
*rabbitPtr -= 2;
if (*rabbitPtr < 1)
*rabbitPtr = 1;
else if (*rabbitPtr > RACE_END)
*rabbitPtr = RACE_END;
}
void printCurrentPositions(const int* const snapperPtr, const int* const bunnyPtr)
{
if (*bunnyPtr == *snapperPtr)
cout << setw(*bunnyPtr) << "OUCH!!!";
else if (*bunnyPtr < *snapperPtr)
cout << setw(*bunnyPtr) << 'H' << setw(*snapperPtr - *bunnyPtr) << 'T';
else
cout << setw(*snapperPtr) << 'T' << setw(*bunnyPtr - *snapperPtr) << 'H';
cout << '\n';
}
第九章
9.4(增强的Time类)
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time();
void setTime( int, int, int );
void printUniversal();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
#include <iostream>
#include <iomanip>
#include <ctime>
#include "Time.h"
using namespace std;
Time::Time()
{
const time_t currentTime = time( 0 );
const tm *localTime = localtime( ¤tTime );
setTime( localTime->tm_hour, localTime->tm_min, localTime->tm_sec );
}
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}
void Time::printUniversal()
{
cout << setfill( '0' ) << setw( 2 ) << hour << ":"
<< setw( 2 ) << minute << ":" << setw( 2 ) << second;
}
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":"
<< setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 )
<< second << ( hour < 12 ? " AM" : " PM" );
}
#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
Time t;
cout << "The universal time is ";
t.printUniversal();
cout << "\nThe standard time is ";
t.printStandard();
cout << endl;
}
9.5(复数类)
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
public:
Complex(double = 0.0, double = 0.0);
Complex add(const Complex&);
Complex subtract(const Complex&);
void printComplex();
void setComplexNumber(double, double);
private:
double realPart;
double imaginaryPart;
};
#endif
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex( double real, double imaginary )
{
setComplexNumber( real, imaginary );
}
Complex Complex::add( const Complex &right )
{
return Complex(
realPart + right.realPart, imaginaryPart + right.imaginaryPart );
}
Complex Complex::subtract( const Complex &right )
{
return Complex(
realPart - right.realPart, imaginaryPart - right.imaginaryPart );
}
void Complex::printComplex()
{
cout << '(' << realPart << ", " << imaginaryPart << ')';
}
void Complex::setComplexNumber( double rp, double ip )
{
realPart = rp;
imaginaryPart = ip;
}
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex a( 1, 7 ), b( 9, 2 ), c;
a.printComplex();
cout << " + ";
b.printComplex();
cout << " = ";
c = a.add( b );
c.printComplex();
cout << '\n';
a.setComplexNumber( 10, 1 );
b.setComplexNumber( 11, 5 );
a.printComplex();
cout << " - ";
b.printComplex();
cout << " = ";
c = a.subtract( b );
c.printComplex();
cout << endl;
}
9.6(有理数类)
#ifndef RATIONAL_H
#define RATIONAL_H
class Rational
{
public:
Rational( int = 0, int = 1 );
Rational addition( const Rational & );
Rational subtraction( const Rational & );
Rational multiplication( const Rational & );
Rational division( const Rational & );
void printRational ();
void printRationalAsDouble();
private:
int numerator;
int denominator;
void reduction();
};
#endif
#include <iostream>
#include "Rational.h"
using namespace std;
Rational::Rational( int n, int d )
{
numerator = n;
denominator = d;
reduction();
}
Rational Rational::addition( const Rational &a )
{
Rational t;
t.numerator = a.numerator * denominator;
t.numerator += a.denominator * numerator;
t.denominator = a.denominator * denominator;
t.reduction();
return t;
}
Rational Rational::subtraction( const Rational &s )
{
Rational t;
t.numerator = s.denominator * numerator;
t.numerator -= denominator * s.numerator;
t.denominator = s.denominator * denominator;
t.reduction();
return t;
}
Rational Rational::multiplication( const Rational &m )
{
Rational t;
t.numerator = m.numerator * numerator;
t.denominator = m.denominator * denominator;
t.reduction();
return t;
}
Rational Rational::division( const Rational &v )
{
Rational t;
t.numerator = v.denominator * numerator;
t.denominator = denominator * v.numerator;
t.reduction();
return t;
}
void Rational::reduction()
{
int largest;
largest = numerator > denominator ? numerator : denominator;
int gcd = 0;
for ( int loop = 2; loop <= largest; loop++ )
if ( numerator % loop == 0 && denominator % loop == 0 )
gcd = loop;
if (gcd != 0)
{
numerator /= gcd;
denominator /= gcd;
}
}
void Rational::printRational ()
{
if ( denominator == 0 )
cout << "\nDIVIDE BY ZERO ERROR!!!" << '\n';
else if ( numerator == 0 )
cout << 0;
else
cout << numerator << '/' << denominator;
}
void Rational::printRationalAsDouble()
{
cout << static_cast< double >( numerator ) / denominator;
}
#include <iostream>
#include "Rational.h"
using namespace std;
int main()
{
Rational c( 2, 6 ), d( 7, 8 ), x;
c.printRational();
cout << " + ";
d.printRational();
x = c.addition( d );
cout << " = ";
x.printRational();
cout << '\n';
x.printRational();
cout << " = ";
x.printRationalAsDouble();
cout << "\n\n";
c.printRational();
cout << " - ";
d.printRational();
x = c.subtraction( d );
cout << " = ";
x.printRational();
cout << '\n';
x.printRational();
cout << " = ";
x.printRationalAsDouble();
cout << "\n\n";
c.printRational();
cout << " x ";
d.printRational();
x = c.multiplication( d );
cout << " = ";
x.printRational();
cout << '\n';
x.printRational();
cout << " = ";
x.printRationalAsDouble();
cout << "\n\n";
c.printRational();
cout << " / ";
d.printRational();
x = c.division( d );
cout << " = ";
x.printRational();
cout << '\n';
x.printRational();
cout << " = ";
x.printRationalAsDouble();
cout << endl;
}
9.7(增强的Time类)
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
void setTime( int, int, int );
void setHour( int );
void setMinute( int );
void setSecond( int );
int getHour();
int getMinute();
int getSecond();
void tick();
void printUniversal();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Time::Time( int hr, int min, int sec )
{
setTime( hr, min, sec );
}
void Time::setTime( int h, int m, int s )
{
setHour( h );
setMinute( m );
setSecond( s );
}
void Time::setHour( int h )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
}
void Time::setMinute( int m )
{
minute = ( m >= 0 && m < 60 ) ? m : 0;
}
void Time::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
}
int Time::getHour()
{
return hour;
}
int Time::getMinute()
{
return minute;
}
int Time::getSecond()
{
return second;
}
void Time::tick()
{
setSecond( getSecond() + 1 );
if ( getSecond() == 0 )
{
setMinute( getMinute() + 1 );
if ( getMinute() == 0 )
setHour( getHour() + 1 );
}
}
void Time::printUniversal()
{
cout << setfill( '0' ) << setw( 2 ) << getHour() << ":"
<< setw( 2 ) << getMinute() << ":" << setw( 2 ) << getSecond();
}
void Time::printStandard()
{
cout << ( ( getHour() == 0 || getHour() == 12 ) ? 12 : getHour() % 12 )
<< ":" << setfill( '0' ) << setw( 2 ) << getMinute()
<< ":" << setw( 2 ) << getSecond() << ( hour < 12 ? " AM" : " PM" );
}
#include <iostream>
#include "Time.h"
using namespace std;
const int MAX_TICKS = 30;
int main()
{
Time t;
t.setTime( 23, 59, 57 );
for ( int ticks = 1; ticks < MAX_TICKS; ++ticks )
{
t.printStandard();
cout << endl;
t.tick();
}
}
9.8(增强的Date类)
#ifndef DATE_H
#define DATE_H
class Date
{
public:
Date( int = 1, int = 1, int = 2000 );
void print();
void setDate( int, int, int );
void setMonth( int );
void setDay( int );
void setYear( int );
int getMonth();
int getDay();
int getYear();
void nextDay();
private:
int month;
int day;
int year;
bool leapYear();
int monthDays();
};
#endif
#include <iostream>
#include "Date.h"
using namespace std;
Date::Date( int m, int d, int y )
{
setDate( m, d, y );
}
void Date::setDate( int mo, int dy, int yr )
{
setMonth( mo );
setDay( dy );
setYear( yr );
}
void Date::setDay( int d )
{
if ( month == 2 && leapYear() )
day = ( d <= 29 && d >= 1 ) ? d : 1;
else
day = ( d <= monthDays() && d >= 1 ) ? d : 1;
}
void Date::setMonth( int m )
{
month = m <= 12 && m >= 1 ? m : 1;
}
void Date::setYear( int y )
{
year = y >= 2000 ? y : 2000;
}
int Date::getDay()
{
return day;
}
int Date::getMonth()
{
return month;
}
int Date::getYear()
{
return year;
}
void Date::print()
{
cout << month << '-' << day << '-' << year << '\n';
}
void Date::nextDay()
{
setDay( day + 1 );
if ( day == 1 )
{
setMonth( month + 1 );
if ( month == 1 )
setYear( year + 1 );
}
}
bool Date::leapYear()
{
if ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )
return true;
else
return false;
}
int Date::monthDays()
{
const int days[12] =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return month == 2 && leapYear() ? 29 : days[month - 1];
}
#include <iostream>
#include "Date.h"
using namespace std;
int main()
{
const int MAXDAYS = 16;
Date d( 12, 24, 2004 );
for ( int loop = 1; loop <= MAXDAYS; ++loop )
{
d.print();
d.nextDay();
}
cout << endl;
}
9.9(合并Time类和Date类)
#ifndef DATEANDTIME_H
#define DATEANDTIME_H
class DateAndTime
{
public:
DateAndTime( int = 1, int = 1, int = 2000,
int = 0, int = 0, int = 0 );
void setDate( int, int, int );
void setMonth( int );
void setDay( int );
void setYear( int );
void nextDay();
void setTime( int, int, int );
void setHour( int );
void setMinute( int );
void setSecond( int );
void tick();
int getMonth();
int getDay();
int getYear();
int getHour();
int getMinute();
int getSecond();
void printStandard();
void printUniversal();
private:
int month;
int day;
int year;
int hour;
int minute;
int second;
bool leapYear();
int monthDays();
};
#endif
#include <iostream>
#include "DateAndTime.h"
using namespace std;
DateAndTime::DateAndTime(
int m, int d, int y, int hr, int min, int sec )
{
setDate( m, d, y );
setTime( hr, min, sec );
}
void DateAndTime::setDate( int mo, int dy, int yr )
{
setMonth( mo );
setDay( dy );
setYear( yr );
}
void DateAndTime::setDay( int d )
{
if ( month == 2 && leapYear() )
day = ( d <= 29 && d >= 1 ) ? d : 1;
else
day = ( d <= monthDays() && d >= 1 ) ? d : 1;
}
void DateAndTime::setMonth( int m )
{
month = m <= 12 && m >= 1 ? m : 1;
}
void DateAndTime::setYear( int y )
{
year = y >= 2000 ? y : 2000;
}
void DateAndTime::nextDay()
{
setDay( day + 1 );
if ( day == 1 )
{
setMonth( month + 1 );
if ( month == 1 )
setYear( year + 1 );
}
}
void DateAndTime::setTime( int hr, int min, int sec )
{
setHour( hr );
setMinute( min );
setSecond( sec );
}
void DateAndTime::setHour( int h )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
}
void DateAndTime::setMinute( int m )
{
minute = ( m >= 0 && m < 60 ) ? m : 0;
}
void DateAndTime::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
}
void DateAndTime::tick()
{
setSecond( second + 1 );
if ( second == 0 )
{
setMinute( minute + 1 );
if ( minute == 0 )
{
setHour( hour + 1 );
if ( hour == 0 )
nextDay();
}
}
}
int DateAndTime::getDay()
{
return day;
}
int DateAndTime::getMonth()
{
return month;
}
int DateAndTime::getYear()
{
return year;
}
int DateAndTime::getHour()
{
return hour;
}
int DateAndTime::getMinute()
{
return minute;
}
int DateAndTime::getSecond()
{
return second;
}
void DateAndTime::printStandard()
{
cout << ( ( hour % 12 == 0 ) ? 12 : hour % 12 ) << ':'
<< ( minute < 10 ? "0" : "" ) << minute << ':'
<< ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM " : " PM " )
<< month << '-' << day << '-' << year << endl;
}
void DateAndTime::printUniversal()
{
cout << ( hour < 10 ? "0" : "" ) << hour << ':'
<< ( minute < 10 ? "0" : "" ) << minute << ':'
<< ( second < 10 ? "0" : "" ) << second << " "
<< month << '-' << day << '-' << year << endl;
}
bool DateAndTime::leapYear()
{
if ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )
return true;
else
return false;
}
int DateAndTime::monthDays()
{
const int days[ 12 ] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return ( month == 2 && leapYear() ) ? 29 : days[ ( month - 1 ) ];
}
#include <iostream>
#include "DateAndTime.h"
using namespace std;
int main()
{
const int MAXTICKS = 30;
DateAndTime d( 12, 31, 2004, 23, 59, 57 );
for ( int ticks = 1; ticks <= MAXTICKS; ticks++ )
{
cout << "Universal time: ";
d.printUniversal();
cout << "Standard time: ";
d.printStandard();
d.tick();
}
cout << endl;
}
9.10(由Time类的设置函数返回错误的指示)
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
bool setTime( int, int, int );
bool setHour( int );
bool setMinute( int );
bool setSecond( int );
int getHour();
int getMinute();
int getSecond();
void printUniversal();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
#include <iostream>
#include "Time.h"
using namespace std;
Time::Time( int hr, int min, int sec )
{
setTime( hr, min, sec );
}
bool Time::setTime( int h, int m, int s )
{
bool hourValid = setHour( h );
bool minuteValid = setMinute( m );
bool secondValid = setSecond( s );
return hourValid && minuteValid && secondValid;
}
bool Time::setHour( int hr )
{
if ( hr >= 0 && hr < 24 )
{
hour = hr;
return true;
}
else
{
hour = 0;
return false;
}
}
bool Time::setMinute( int min )
{
if ( min >= 0 && min < 60 )
{
minute = min;
return true;
}
else
{
minute = 0;
return false;
}
}
bool Time::setSecond( int sec )
{
if ( sec >= 0 && sec < 60 )
{
second = sec;
return true;
}
else
{
second = 0;
return false;
}
}
int Time::getHour()
{
return hour;
}
int Time::getMinute()
{
return minute;
}
int Time::getSecond()
{
return second;
}
void Time::printUniversal()
{
cout << ( hour < 10 ? "0" : "" ) << hour << ':'
<< ( minute < 10 ? "0" : "" ) << minute << ':'
<< ( second < 10 ? "0" : "" ) << second;
}
void Time::printStandard()
{
cout << ( ( hour % 12 == 0 ) ? 12 : hour % 12 ) << ':'
<< ( minute < 10 ? "0": "" ) << minute << ':'
<< ( second < 10 ? "0": "" ) << second
<< ( hour < 12 ? " AM" : " PM" );
}
#include <iostream>
#include "Time.h"
using namespace std;
int getMenuChoice();
int main()
{
Time time;
int choice = getMenuChoice();
int hours;
int minutes;
int seconds;
while ( choice != 4 )
{
switch ( choice )
{
case 1:
cout << "Enter Hours: ";
cin >> hours;
if ( !time.setHour( hours ) )
cout << "Invalid hours." << endl;
break;
case 2:
cout << "Enter Minutes: ";
cin >> minutes;
if ( !time.setMinute( minutes ) )
cout << "Invalid minutes." << endl;
break;
case 3:
cout << "Enter Seconds: ";
cin >> seconds;
if ( !time.setSecond( seconds ) )
cout << "Invalid seconds." << endl;
break;
}
cout << "Hour: " << time.getHour() << " Minute: "
<< time.getMinute() << " Second: " << time.getSecond() << endl;
cout << "Universal time: ";
time.printUniversal();
cout << " Standard time: ";
time.printStandard();
cout << endl;
choice = getMenuChoice();
}
}
int getMenuChoice()
{
int choice;
cout << "1. Set Hour\n2. Set Minute\n3. Set Second\n"
<< "4. Exit\nChoice: " << endl;
cin >> choice;
return choice;
}
9.11(Rectangle类)
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
public:
Rectangle( double = 1.0, double = 1.0 );
void setWidth( double w );
void setLength( double l );
double getWidth();
double getLength();
double perimeter();
double area();
private:
double length;
double width;
};
#endif
#include "Rectangle.h"
Rectangle::Rectangle( double w, double l )
{
setWidth(w);
setLength(l);
}
void Rectangle::setWidth( double w )
{
width = w > 0 && w < 20.0 ? w : 1.0;
}
void Rectangle::setLength( double l )
{
length = l > 0 && l < 20.0 ? l : 1.0;
}
double Rectangle::getWidth()
{
return width;
}
double Rectangle::getLength()
{
return length;
}
double Rectangle::perimeter()
{
return 2 * ( width + length );
}
double Rectangle::area()
{
return width * length;
}
#include <iostream>
#include <iomanip>
#include "Rectangle.h"
using namespace std;
int main()
{
Rectangle a, b( 4.0, 5.0 ), c( 67.0, 888.0 );
cout << fixed;
cout << setprecision( 1 );
cout << "a: length = " << a.getLength() << "; width = "
<< a.getWidth() << "; perimeter = " << a.perimeter()
<< "; area = " << a.area() << '\n';
cout << "b: length = " << b.getLength() << "; width = "
<< b.getWidth() << "; perimeter = " << b.perimeter()
<< "; area = " << b.area() << '\n';
cout << "c: length = " << c.getLength() << "; width = "
<< c.getWidth() << "; perimeter = " << c.perimeter()
<< "; area = " << c.area() << endl;
}
9.12(增强的Rectangle类)
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(double = 0.0, double = 0.0);
void setX(double);
void setY(double);
double getX();
double getY();
private:
double x;
double y;
};
#endif
#include "Point.h"
Point::Point( double xCoord, double yCoord )
{
setX( xCoord );
setY( yCoord );
}
void Point::setX( double xCoord )
{
x = ( xCoord >= 0.0 && xCoord <= 20.0 ) ? xCoord : 0.0;
}
void Point::setY( double yCoord )
{
y = ( yCoord >= 0.0 && yCoord <= 20.0 ) ? yCoord : 0.0;
}
double Point::getX()
{
return x;
}
double Point::getY()
{
return y;
}
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "Point.h"
class Rectangle
{
public:
Rectangle(Point = Point(0.0, 1.0), Point = Point(1.0, 1.0),
Point = Point(1.0, 0.0), Point = Point(0.0, 0.0));
void setCoord(Point, Point, Point, Point);
double length();
double width();
void perimeter();
void area();
bool square();
Point point1;
Point point2;
Point point3;
Point point4;
};
#endif
#include <iostream>
#include <iomanip>
#include <cmath>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle( Point a, Point b, Point c, Point d )
{
setCoord(a, b, c, d);
}
double Rectangle::length()
{
double side1 = fabs(point4.getY() - point1.getY());
double side2 = fabs(point2.getX() - point1.getX());
double length = (side1 > side2 ? side1 : side2);
return length;
}
double Rectangle::width()
{
double side1 = fabs(point4.getY() - point1.getY());
double side2 = fabs(point2.getX() - point1.getX());
double width = (side1 < side2 ? side1 : side2);
return width;
}
void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 )
{
if ((p1.getY() == p2.getY() && p1.getX() == p4.getX()
&& p2.getX() == p3.getX() && p3.getY() == p4.getY()))
{
point1 = p1;
point2 = p2;
point3 = p3;
point4 = p4;
}
else
{
cout << "Coordinates do not form a rectangle!\n"
<< "Use default values.\n";
point1 = Point(0.0, 1.0);
point2 = Point(1.0, 1.0);
point3 = Point(1.0, 0.0);
point4 = Point(0.0, 0.0);
}
}
void Rectangle::perimeter()
{
cout << fixed << "\nThe perimeter is: " << setprecision(1)
<< 2 * (length() + width()) << endl;
}
void Rectangle::area()
{
cout << fixed << "The area is: " << setprecision(1)
<< length() * width() << endl;
}
bool Rectangle::square()
{
return length() == width();
}
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main()
{
Point w(1.0, 1.0);
Point x(5.0, 1.0);
Point y(5.0, 3.0);
Point z(1.0, 3.0);
Point j(0.0, 0.0);
Point k(1.0, 0.0);
Point m(1.0, 1.0);
Point n(0.0, 1.0);
Point v(99.0, -2.3);
Rectangle rectangles[4];
for (int i = 0; i < 4; i++)
{
cout << "Rectangle" << i + 1 << ":\n";
switch (i)
{
case 0:
rectangles[i] = Rectangle(z, y, x, w);
break;
case 1:
rectangles[i] = Rectangle(j, k, m, n);
break;
case 2:
rectangles[i] = Rectangle(w, x, m, n);
break;
case 3:
rectangles[i] = Rectangle(v, x, y, z);
break;
}
cout << "length = " << rectangles[i].length();
cout << "\nwidth = " << rectangles[i].width();
rectangles[i].perimeter();
rectangles[i].area();
cout << "The rectangle "
<< (rectangles[i].square() ? "is" : "is not")
<< " a square.\n";
}
}
9.13(增强的Rectangle类)
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(double = 0.0, double = 0.0);
void setX(double);
void setY(double);
double getX();
double getY();
private:
double x;
double y;
};
#endif
#include "Point.h"
Point::Point( double xCoord, double yCoord )
{
setX( xCoord );
setY( yCoord );
}
void Point::setX( double xCoord )
{
x = ( xCoord >= 0.0 && xCoord <= 20.0 ) ? xCoord : 0.0;
}
void Point::setY( double yCoord )
{
y = ( yCoord >= 0.0 && yCoord <= 20.0 ) ? yCoord : 0.0;
}
double Point::getX()
{
return x;
}
double Point::getY()
{
return y;
}
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "Point.h"
class Rectangle
{
public:
Rectangle(Point = Point(0.0, 1.0), Point = Point(1.0, 1.0),
Point = Point(1.0, 0.0), Point = Point(0.0, 0.0),
char = '*', char = '*');
void setCoord(Point, Point, Point, Point);
double length();
double width();
void perimeter();
void area();
bool square();
void draw();
void setPerimeterCharacter(char);
void setFillCharacter(char);
private:
Point point1;
Point point2;
Point point3;
Point point4;
char fillCharacter;
char perimeterCharacter;
};
#endif
#include <iostream>
#include <iomanip>
#include <cmath>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle( Point a, Point b, Point c, Point d,
char fillChar, char perimeterChar )
{
setCoord(a, b, c, d);
setFillCharacter(fillChar);
setPerimeterCharacter(perimeterChar);
}
void Rectangle::setCoord( Point p1, Point p2, Point p3, Point p4 )
{
if ((p1.getY() == p2.getY() && p1.getX() == p4.getX()
&& p2.getX() == p3.getX() && p3.getY() == p4.getY()))
{
point1 = p1;
point2 = p2;
point3 = p3;
point4 = p4;
}
else
{
cout << "Coordinates do not form a rectangle!\n"
<< "Use default values.\n";
point1 = Point(0.0, 1.0);
point2 = Point(1.0, 1.0);
point3 = Point(1.0, 0.0);
point4 = Point(0.0, 0.0);
}
}
double Rectangle::length()
{
double side1 = fabs( point4.getY() - point1.getY() );
double side2 = fabs( point2.getX() - point1.getX() );
double length = ( side1 > side2 ? side1 : side2 );
return length;
}
double Rectangle::width()
{
double side1 = fabs(point4.getY() - point1.getY());
double side2 = fabs(point2.getX() - point1.getX());
double width = (side1 < side2 ? side1 : side2);
return width;
}
void Rectangle::perimeter()
{
cout << fixed << "\nThe perimeter is: " << setprecision(1)
<< 2 * (length() + width()) << endl;
}
void Rectangle::area()
{
cout << fixed << "The area is: " << setprecision(1)
<< length() * width() << endl;
}
bool Rectangle::square()
{
return length() == width();
}
void Rectangle::draw()
{
for (double y = 25.0; y >= 0.0; y--)
{
for (double x = 0.0; x <= 25.0; x++)
{
if ((point1.getX() == x && point1.getY() == y) ||
(point4.getX() == x && point4.getY() == y))
{
while (x <= point2.getX())
{
cout << perimeterCharacter;
x++;
}
cout << '.';
}
else if (((x <= point4.getX() && x >= point1.getX())) &&
point4.getY() >= y && point1.getY() <= y)
{
cout << perimeterCharacter;
for (x++; x < point2.getX(); )
{
cout << fillCharacter;
x++;
}
cout << perimeterCharacter;
}
else
cout << '.';
}
cout << '\n';
}
}
void Rectangle::setFillCharacter( char fillChar )
{
fillCharacter = fillChar;
}
void Rectangle::setPerimeterCharacter( char perimeterChar )
{
perimeterCharacter = perimeterChar;
}
9.14(HugeInteger类)
#ifndef HUGEINTEGER_H
#define HUGEINTEGER_H
#include <string>
using namespace std;
class HugeInteger
{
public:
HugeInteger(long = 0);
HugeInteger(const string&);
HugeInteger add(HugeInteger);
HugeInteger add(int);
HugeInteger add(const string&);
HugeInteger subtract(HugeInteger);
HugeInteger subtract(int);
HugeInteger subtract(const string&);
bool isEqualTo(HugeInteger);
bool isNotEqualTo(HugeInteger);
bool isGreaterThan(HugeInteger);
bool isLessThan(HugeInteger);
bool isGreaterThanOrEqualTo(HugeInteger);
bool isLessThanOrEqualTo(HugeInteger);
bool isZero();
void input(const string&);
void output();
private:
short integer[40];
};
#endif
#include <iostream>
#include "HugeInteger.h"
using namespace std;
HugeInteger::HugeInteger( long value )
{
for ( int i = 0; i < 40; i++ )
integer[ i ] = 0;
for (int j = 39; value != 0 && j >= 0; j--)
{
integer[j] = static_cast<short>(value % 10);
value /= 10;
}
}
HugeInteger::HugeInteger( const string &string )
{
input( string );
}
HugeInteger HugeInteger::add(HugeInteger op2)
{
HugeInteger temp;
int carry = 0;
for (int i = 39; i >= 0; i--)
{
temp.integer[i] = integer[i] + op2.integer[i] + carry;
if (temp.integer[i] > 9)
{
temp.integer[i] %= 10;
carry = 1;
}
else
carry = 0;
}
return temp;
}
HugeInteger HugeInteger::add( int op2 )
{
return add( HugeInteger( op2 ) );
}
HugeInteger HugeInteger::add( const string &op2 )
{
return add( HugeInteger( op2 ) );
}
HugeInteger HugeInteger::subtract( HugeInteger op2 )
{
if ( isLessThan( op2 ) )
{
cout << "Error: Tried to subtract larger value from smaller value."
<< endl;
return HugeInteger( "0" );
}
HugeInteger result( "0" );
bool minusOne = false;
for (int i = 39; i >= 0; i--)
{
int topValue = integer[i];
int bottomValue = op2.integer[i];
if (minusOne)
{
if (topValue == 0)
topValue = 9;
else
{
topValue -= 1;
minusOne = false;
}
}
if (topValue >= bottomValue)
result.integer[i] = topValue - bottomValue;
else
{
topValue += 10;
minusOne = true;
result.integer[i] = topValue - bottomValue;
}
}
return result;
}
HugeInteger HugeInteger::subtract( int op2 )
{
return subtract( HugeInteger( op2 ) );
}
HugeInteger HugeInteger::subtract( const string &op2 )
{
return subtract( HugeInteger( op2 ) );
}
bool HugeInteger::isEqualTo( HugeInteger x )
{
for ( int i = 39; i >= 0; i-- )
if ( integer[ i ] != x.integer[ i ] )
return false;
return true;
}
bool HugeInteger::isNotEqualTo( HugeInteger x )
{
return !( isEqualTo( x ) );
}
bool HugeInteger::isGreaterThan( HugeInteger x )
{
return ( x.isLessThan( *this ) );
}
bool HugeInteger::isLessThan( HugeInteger x )
{
for ( int i = 0; i < 40; i++ )
if ( integer[ i ] > x.integer[ i ] )
return false;
else if ( integer[ i ] < x.integer[ i ] )
return true;
return false;
}
bool HugeInteger::isGreaterThanOrEqualTo( HugeInteger x )
{
return ( !isLessThan( x ) );
}
bool HugeInteger::isLessThanOrEqualTo( HugeInteger x )
{
return ( isEqualTo( x ) || isLessThan( x ) );
}
bool HugeInteger::isZero()
{
for (int i = 0; i < 40; i++ )
if ( integer[ i ] != 0 )
return false;
return true;
}
void HugeInteger::input( const string &val )
{
for ( int i = 0; i < 40; i++ )
integer[ i ] = 0;
int length = val.size();
for ( int j = 40 - length, k = 0; j < 40; j++, k++ )
if ( isdigit( val[ k ] ) )
integer[ j ] = val[ k ] - '0';
}
void HugeInteger::output()
{
int i;
for ( i = 0; ( integer[ i ] == 0 ) && ( i <= 39 ); i++ )
;
if (i == 40)
cout << 0;
else
for ( ; i <= 39; i++ )
cout << integer[ i ];
}
#include <iostream>
#include "HugeInteger.h"
using namespace std;
int main()
{
HugeInteger n1( 7654321 );
HugeInteger n2( "100000000000000" );
HugeInteger n3;
HugeInteger n4( 5 );
HugeInteger n5;
n5 = n1.add( n2 );
n1.output();
cout << " + ";
n2.output();
cout << " = ";
n5.output();
cout << "\n\n";
n5 = n2.subtract( n4 );
n2.output();
cout<< " - ";
n4.output();
cout << " = ";
n5.output();
cout << "\n\n";
if ( n2.isEqualTo( n2 ) == true )
{
n2.output();
cout << " is equal to ";
n2.output();
cout << "\n\n";
}
if ( n1.isNotEqualTo( n2 ) == true )
{
n1.output();
cout << " is not equal to ";
n2.output();
cout << "\n\n";
}
if ( n2.isGreaterThan( n1 ) == true )
{
n2.output();
cout << " is greater than ";
n1.output();
cout << "\n\n";
}
if ( n4.isLessThan( n2 ) == true )
{
n4.output();
cout << " is less than ";
n2.output();
cout << "\n\n";
}
if ( n4.isLessThanOrEqualTo( n4 ) == true )
{
n4.output();
cout << " is less than or equal to ";
n4.output();
cout << "\n\n";
}
if ( n4.isLessThanOrEqualTo( n2 ) == true )
{
n4.output();
cout << " is less than or equal to ";
n2.output();
cout << "\n\n";
}
if ( n3.isGreaterThanOrEqualTo( n3 ) == true )
{
n3.output();
cout << " is greater than or equal to ";
n3.output();
cout << "\n\n";
}
if ( n2.isGreaterThanOrEqualTo( n3 ) == true )
{
n2.output();
cout << " is greater than or equal to ";
n3.output();
cout << "\n\n";
}
if ( n3.isZero() == true )
{
cout << "n3 contains ";
n3.output();
cout << "\n\n";
}
}
9.15(TicTacToe类)
#ifndef TICTACTOE_H
#define TICTACTOE_H
class TicTacToe
{
private:
enum Status { WIN, DRAW, CONTINUE };
int board[3][3];
public:
TicTacToe();
void makeMove();
void printBoard();
bool validMove(int, int);
bool xoMove(int);
Status gameStatus();
};
#endif
#include <iostream>
#include <iomanip>
#include "TicTacToe.h"
using namespace std;
TicTacToe::TicTacToe()
{
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++)
board[j][k] = ' ';
}
bool TicTacToe::validMove( int r, int c )
{
return r >= 0 && r < 3 && c >= 0 && c < 3 && board[r][c] == ' ';
}
TicTacToe::Status TicTacToe::gameStatus()
{
int a;
if (board[0][0] != ' ' && board[0][0] == board[1][1] &&
board[0][0] == board[2][2])
return WIN;
else if (board[2][0] != ' ' && board[2][0] ==
board[1][1] && board[2][0] == board[0][2])
return WIN;
for (a = 0; a < 3; ++a)
if (board[a][0] != ' ' && board[a][0] ==
board[a][1] && board[a][0] == board[a][2])
return WIN;
for (a = 0; a < 3; ++a)
if (board[0][a] != ' ' && board[0][a] ==
board[1][a] && board[0][a] == board[2][a])
return WIN;
for (int r = 0; r < 3; ++r)
for (int c = 0; c < 3; ++c)
if (board[r][c] == ' ')
return CONTINUE;
return DRAW;
}
void TicTacToe::printBoard()
{
cout << " 0 1 2\n\n";
for ( int r = 0; r < 3; ++r )
{
cout << r;
for ( int c = 0; c < 3; ++c )
{
cout << setw( 3 ) << static_cast< char > ( board[ r ][ c ] );
if ( c != 2 )
cout << " |";
}
if ( r != 2 )
cout << "\n ____|____|____\n | | \n";
}
cout << "\n\n";
}
void TicTacToe::makeMove()
{
printBoard();
while ( true )
{
if ( xoMove( 'X' ) )
break;
else if ( xoMove( 'O' ) )
break;
}
}
bool TicTacToe::xoMove( int symbol )
{
int x;
int y;
do
{
cout << "Player " << static_cast<char>(symbol)
<< " enter move: ";
cin >> x >> y;
cout << '\n';
} while (!validMove(x, y));
board[ x ][ y ] = symbol;
printBoard();
Status xoStatus = gameStatus();
if ( xoStatus == WIN )
{
cout << "Player " << static_cast< char >( symbol ) << " wins!\n";
return true;
}
else if ( xoStatus == DRAW )
{
cout << "Game is a draw.\n";
return true;
}
else
return false;
}
#include "TicTacToe.h"
int main()
{
TicTacToe g;
g.makeMove();
}
9.19(修改Date类)
#ifndef DATE_H
#define DATE_H
#include <string>
using namespace std;
class Date
{
public:
Date();
Date(int, int);
Date(int, int, int);
Date(string, int, int);
void setDay(int);
void setMonth(int);
void print() const;
void printDDDYYYY() const;
void printMMDDYY() const;
void printMonthDDYYYY() const;
~Date();
private:
int month;
int day;
int year;
int checkDay(int) const;
int daysInMonth(int) const;
bool isLeapYear() const;
int convertDDToDDD() const;
void setMMDDFromDDD(int);
string convertMMToMonth(int) const;
void setMMFromMonth(string);
int convertYYYYToYY() const;
void setYYYYFromYY(int);
};
#endif
#include <iostream>
#include <iomanip>
#include <ctime>
#include "Date.h"
using namespace std;
Date::Date()
{
struct tm *ptr;
time_t t = time( 0 );
ptr = localtime( &t );
day = ptr->tm_mday;
month = 1 + ptr->tm_mon;
year = ptr->tm_year + 1900;
}
Date::Date( int ddd, int yyyy )
{
year = yyyy;
setMMDDFromDDD( ddd );
}
Date::Date( int mm, int dd, int yy )
{
setYYYYFromYY( yy );
setMonth( mm );
setDay( dd );
}
Date::Date( string monthName, int dd, int yyyy )
{
setMMFromMonth( monthName );
setDay( dd );
year = yyyy;
}
void Date::setDay( int d )
{
day = checkDay( d );
}
void Date::setMonth( int m )
{
if ( m > 0 && m <= 12 )
month = m;
else
{
month = 1;
cout << "Invalid month (" << m << ") set to 1.\n";
}
}
void Date::print() const
{
cout << month << '/' << day << '/' << year << endl;
}
void Date::printDDDYYYY() const
{
cout << convertDDToDDD() << ' ' << year << endl;
}
void Date::printMMDDYY() const
{
cout << setw( 2 ) << setfill( '0' ) << month << '/'
<< setw( 2 ) << setfill( '0' ) << day << '/'
<< setw( 2 ) << setfill( '0' ) << convertYYYYToYY() << endl;
}
void Date::printMonthDDYYYY() const
{
cout << convertMMToMonth( month ) << ' ' << day << ", " << year
<< endl;
}
Date::~Date()
{
cout << "Date object destructor for date ";
print();
cout << endl;
}
int Date::checkDay( int testDay ) const
{
if ( testDay > 0 && testDay <= daysInMonth( month ) )
return testDay;
if ( month == 2 && testDay == 29 && isLeapYear() )
return testDay;
cout << "Invalid day (" << testDay << ") set to 1.\n";
return 1;
}
int Date::daysInMonth( int m ) const
{
if ( isLeapYear() && m == 2 )
return 29;
static const int daysPerMonth[ 13 ] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return daysPerMonth[ m ];
}
bool Date::isLeapYear() const
{
if ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )
return true;
else
return false;
}
int Date::convertDDToDDD() const
{
int ddd = 0;
for ( int i = 1; i < month; i++ )
ddd += daysInMonth( i );
ddd += day;
return ddd;
}
void Date::setMMDDFromDDD( int ddd )
{
int dayTotal = 0;
int m;
for ( m = 1; m <= 12 && ( dayTotal + daysInMonth( m ) ) < ddd; m++ )
dayTotal += daysInMonth( m );
setMonth( m );
setDay( ddd - dayTotal );
}
string Date::convertMMToMonth( int mm ) const
{
static const string months[] =
{ "", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
return months[ mm ];
}
void Date::setMMFromMonth( string m )
{
bool matchFound = false;
for ( int i = 1; i <= 12 && !matchFound; i++ )
{
string tempMonth = convertMMToMonth( i );
if ( tempMonth == m )
{
setMonth( i );
matchFound = true;
}
}
if ( !matchFound )
{
cout << "Invalid month name (" << month << "). month set to 1.\n";
setMonth( 1 );
}
}
int Date::convertYYYYToYY() const
{
return ( year >= 2000 ? year - 2000 : year - 1900 );
}
void Date::setYYYYFromYY( int yy )
{
year = ( yy < 7 ? yy + 2000 : yy + 1900 );
}
#include <iostream>
#include "Date.h"
using namespace std;
int main()
{
Date date1( 256, 1999 );
Date date2( 3, 25, 04 );
Date date3( "September", 1, 2000 );
Date date4;
date1.print();
date2.print();
date3.print();
date4.print();
cout << '\n';
date1.printDDDYYYY();
date2.printDDDYYYY();
date3.printDDDYYYY();
date4.printDDDYYYY();
cout << '\n';
date1.printMMDDYY();
date2.printMMDDYY();
date3.printMMDDYY();
date4.printMMDDYY();
cout << '\n';
date1.printMonthDDYYYY();
date2.printMonthDDYYYY();
date3.printMonthDDYYYY();
date4.printMonthDDYYYY();
cout << endl;
}
9.20(SavingAccount类)
#ifndef SAVINGS_ACCOUNT_H
#define SAVINGS_ACCOUNT_H
class SavingsAccount
{
public:
SavingsAccount( double b )
{
savingsBalance = ( b >= 0.0 ? b : 0.0 );
}
void calculateMonthlyInterest();
static void modifyInterestRate( double );
void printBalance() const;
private:
double savingsBalance;
static double annualInterestRate;
};
#endif
#include <iostream>
#include <iomanip>
#include "SavingsAccount.h"
using namespace std;
double SavingsAccount::annualInterestRate = 0.0;
void SavingsAccount::calculateMonthlyInterest()
{
savingsBalance += savingsBalance * ( annualInterestRate / 12.0 );
}
void SavingsAccount::modifyInterestRate( double i )
{
annualInterestRate = ( i >= 0.0 && i <= 1.0 ) ? i : 0.03;
}
void SavingsAccount::printBalance() const
{
cout << fixed << '$' << setprecision( 2 ) << savingsBalance;
}
#include <iostream>
#include <iomanip>
#include "SavingsAccount.h"
using namespace std;
int main()
{
SavingsAccount saver1( 2000.0 );
SavingsAccount saver2( 3000.0 );
SavingsAccount::modifyInterestRate( .03 );
cout << "Initial balances:\nSaver 1: ";
saver1.printBalance();
cout << "\tSaver 2: ";
saver2.printBalance();
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
cout << "\n\nBalances after 1 month's interest applied at .03:\n"
<< "Saver 1: ";
saver1.printBalance();
cout << "\tSaver 2: ";
saver2.printBalance();
SavingsAccount::modifyInterestRate( .04 );
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
cout << "\n\nBalances after 1 month's interest applied at .04:\n"
<< "Saver 1: ";
saver1.printBalance();
cout << "\tSaver 2: ";
saver2.printBalance();
cout << endl;
}
9.21(IntegerSet类)
#ifndef INTEGER_SET_H
#define INTEGER_SET_H
#include <vector>
using namespace std;
class IntegerSet
{
public:
static const int setSize = 101;
IntegerSet()
: set(setSize)
{
}
IntegerSet(int[], int);
IntegerSet unionOfSets(const IntegerSet&) const;
IntegerSet intersectionOfSets(const IntegerSet&) const;
void inputSet();
void insertElement(int);
void deleteElement(int);
void printSet() const;
bool isEqualTo(const IntegerSet&) const;
private:
vector< bool > set;
int validEntry(int x) const
{
return (x >= 0 && x < setSize);
}
};
#endif
#include <iostream>
#include <iomanip>
#include "IntegerSet.h"
using namespace std;
IntegerSet::IntegerSet(int array[], int size)
: set(setSize)
{
for (int i = 0; i < size; i++)
insertElement(array[i]);
}
void IntegerSet::inputSet()
{
int number;
do
{
cout << "Enter an element (-1 to end): ";
cin >> number;
if (validEntry(number))
set[number] = true;
else if (number != -1)
cerr << "Invalid Element\n";
} while (number != -1);
cout << "Entry complete\n";
}
void IntegerSet::printSet() const
{
int x = 1;
bool empty = true;
cout << '{';
for (int i = 0; i < setSize; i++)
{
if (set[i])
{
cout << setw(4) << i << (x % 10 == 0 ? "\n" : "");
empty = false;
x++;
}
}
if (empty)
cout << setw(4) << "---";
cout << setw(4) << "}" << '\n';
}
IntegerSet IntegerSet::unionOfSets(const IntegerSet& r) const
{
IntegerSet temp;
for (int i = 0; i < setSize; i++)
temp.set[i] = set[i] || r.set[i];
return temp;
}
IntegerSet IntegerSet::intersectionOfSets(const IntegerSet& r) const
{
IntegerSet temp;
for (int i = 0; i < setSize; i++)
temp.set[i] = set[i] && r.set[i];
return temp;
}
void IntegerSet::insertElement(int k)
{
if (validEntry(k))
set[k] = true;
else
cerr << "Invalid insert attempted!\n";
}
void IntegerSet::deleteElement(int k)
{
if (validEntry(k))
set[k] = false;
else
cerr << "Invalid delete attempted!\n";
}
bool IntegerSet::isEqualTo(const IntegerSet& r) const
{
for (int i = 0; i < setSize; i++)
if (set[i] != r.set[i])
return false;
return true;
}
#include <iostream>
#include "IntegerSet.h"
using namespace std;
int main()
{
IntegerSet a;
IntegerSet b;
IntegerSet c;
IntegerSet d;
cout << "Enter set A:\n";
a.inputSet();
cout << "\nEnter set B:\n";
b.inputSet();
c = a.unionOfSets(b);
d = a.intersectionOfSets(b);
cout << "\nUnion of A and B is:\n";
c.printSet();
cout << "Intersection of A and B is:\n";
d.printSet();
if (a.isEqualTo(b))
cout << "Set A is equal to set B\n";
else
cout << "Set A is not equal to set B\n";
cout << "\nInserting 77 into set A...\n";
a.insertElement(77);
cout << "Set A is now:\n";
a.printSet();
cout << "\nDeleting 77 from set A...\n";
a.deleteElement(77);
cout << "Set A is now:\n";
a.printSet();
const int arraySize = 10;
int intArray[arraySize] = { 25, 67, 2, 9, 99, 105, 45, -5, 100, 1 };
IntegerSet e(intArray, arraySize);
cout << "\nSet E is:\n";
e.printSet();
cout << endl;
}
9.22(修改类Time)
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time(int = 0, int = 0, int = 0);
Time& setTime(int, int, int);
Time& setHour(int);
Time& setMinute(int);
Time& setSecond(int);
int getHour() const;
int getMinute() const;
int getSecond() const;
void printUniversal() const;
void printStandard() const;
private:
int totalSeconds;
};
#endif
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Time::Time(int hr, int min, int sec)
{
setTime(hr, min, sec);
}
Time& Time::setTime(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
return *this;
}
Time& Time::setHour(int h)
{
int hours = (h >= 0 && h < 24) ? h : 0;
totalSeconds = (hours * 3600) + (getMinute() * 60) + getSecond();
return *this;
}
Time& Time::setMinute(int m)
{
int minutes = (m >= 0 && m < 60) ? m : 0;
totalSeconds = (getHour() * 3600) + (minutes * 60) + getSecond();
return *this;
}
Time& Time::setSecond(int s)
{
int seconds = (s >= 0 && s < 60) ? s : 0;
totalSeconds = (getHour() * 3600) + (getMinute() * 60) + seconds;
return *this;
}
int Time::getSecond() const
{
return ((totalSeconds % 3600) % 60);
}
int Time::getMinute() const
{
return ((totalSeconds % 3600) / 60);
}
int Time::getHour() const
{
return (totalSeconds / 3600);
}
void Time::printUniversal() const
{
cout << setfill('0') << setw(2) << getHour() << ":"
<< setw(2) << getMinute() << ":" << setw(2) << getSecond();
}
void Time::printStandard() const
{
int hour = getHour();
cout << ((hour == 0 || hour == 12) ? 12 : hour % 12)
<< ":" << setfill('0') << setw(2) << getMinute()
<< ":" << setw(2) << getSecond() << (hour < 12 ? " AM" : " PM");
}
#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
Time t;
t.setHour(18).setMinute(30).setSecond(22);
cout << "Universal time: ";
t.printUniversal();
cout << "\nStandard time: ";
t.printStandard();
cout << "\n\nNew standard time: ";
t.setTime(20, 20, 20).printStandard();
cout << endl;
}
9.23(洗牌和发牌)
#ifndef CARD_H
#define CARD_H
#include <string>
using namespace std;
class Card
{
public:
static const int totalFaces = 13;
static const int totalSuits = 4;
Card(int cardFace, int cardSuit);
string toString() const;
int getFace() const
{
return face;
}
int getSuit() const
{
return suit;
}
private:
int face;
int suit;
static const string faceNames[totalFaces];
static const string suitNames[totalSuits];
};
#endif
#include "Card.h"
Card::Card( int cardFace, int cardSuit )
{
face = ( cardFace >= 0 && cardFace < totalFaces ) ? cardFace : 0;
suit = ( cardSuit >= 0 && cardSuit < totalSuits ) ? cardSuit : 0;
}
string Card::toString() const
{
return faceNames[ face ] + " of " + suitNames[ suit ];
}
const string Card::faceNames[ totalFaces ] =
{ "Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
const string Card::suitNames[ totalSuits ] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
#ifndef DECK_OF_CARDS_H
#define DECK_OF_CARDS_H
#include <vector>
#include "Card.h"
using namespace std;
class DeckOfCards
{
public:
DeckOfCards();
void shuffle();
Card dealCard();
bool moreCards() const;
private:
vector< Card > deck;
unsigned currentCard;
};
#endif
#include <cstdlib>
#include <ctime>
#include "DeckOfCards.h"
using namespace std;
DeckOfCards::DeckOfCards()
{
currentCard = 0;
for (int i = 0; i < Card::totalFaces * Card::totalSuits; ++i)
{
Card card(i % Card::totalFaces, i / Card::totalFaces);
deck.push_back(card);
}
srand(time(0));
}
void DeckOfCards::shuffle()
{
currentCard = 0;
for (unsigned first = 0; first < deck.size(); ++first)
{
unsigned second = rand() % deck.size();
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
}
Card DeckOfCards::dealCard()
{
return deck[currentCard++];
}
bool DeckOfCards::moreCards() const
{
return currentCard < deck.size();
}
#include <iostream>
#include <iomanip>
#include "DeckOfCards.h"
using namespace std;
int main()
{
DeckOfCards myDeckOfCards;
myDeckOfCards.shuffle();
for (int i = 1; myDeckOfCards.moreCards(); i++)
{
cout << left << setw(19) << myDeckOfCards.dealCard().toString();
if (i % 4 == 0)
cout << endl;
}
}
9.24(洗牌和发牌)
#ifndef CARD_H
#define CARD_H
#include <string>
using namespace std;
class Card
{
public:
static const int totalFaces = 13;
static const int totalSuits = 4;
Card(int cardFace, int cardSuit);
string toString() const;
int getFace() const
{
return face;
}
int getSuit() const
{
return suit;
}
private:
int face;
int suit;
static const string faceNames[totalFaces];
static const string suitNames[totalSuits];
};
#endif
#include "Card.h"
Card::Card(int cardFace, int cardSuit)
{
face = (cardFace >= 0 && cardFace < totalFaces) ? cardFace : 0;
suit = (cardSuit >= 0 && cardSuit < totalSuits) ? cardSuit : 0;
}
string Card::toString() const
{
return faceNames[face] + " of " + suitNames[suit];
}
const string Card::faceNames[totalFaces] =
{ "Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
const string Card::suitNames[totalSuits] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
#ifndef DECK_OF_CARDS_H
#define DECK_OF_CARDS_H
#include <vector>
#include "Card.h"
using namespace std;
class DeckOfCards
{
public:
DeckOfCards();
void shuffle();
Card dealCard();
bool moreCards() const;
private:
vector< Card > deck;
unsigned currentCard;
};
#endif
#include <cstdlib>
#include <ctime>
#include "DeckOfCards.h"
using namespace std;
DeckOfCards::DeckOfCards()
{
currentCard = 0;
for (int i = 0; i < Card::totalFaces * Card::totalSuits; ++i)
{
Card card(i % Card::totalFaces, i / Card::totalFaces);
deck.push_back(card);
}
srand(time(0));
}
void DeckOfCards::shuffle()
{
currentCard = 0;
for (unsigned first = 0; first < deck.size(); ++first)
{
unsigned second = rand() % deck.size();
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
}
Card DeckOfCards::dealCard()
{
return deck[ currentCard++ ];
}
bool DeckOfCards::moreCards() const
{
return currentCard < deck.size();
}
#ifndef HAND_H
#define HAND_H
#include <string>
#include <vector>
#include "Card.h"
#include "DeckOfCards.h"
using namespace std;
class Hand
{
public:
Hand(DeckOfCards& deck);
void print() const;
bool pair() const;
bool twoPair() const;
bool threeOfAKind() const;
bool fourOfAKind() const;
bool flush() const;
bool straight() const;
private:
vector< Card > hand;
vector< int > faceCount;
};
#endif
#include <iostream>
#include "Hand.h"
using namespace std;
Hand::Hand(DeckOfCards& deck)
: faceCount(Card::totalFaces)
{
for (unsigned i = 0; i < 5; ++i)
hand.push_back(deck.dealCard());
for (unsigned i = 0; i < hand.size(); ++i)
++faceCount[hand[i].getFace()];
}
void Hand::print() const
{
cout << "Hand is:\n";
for (unsigned i = 0; i < hand.size(); ++i)
cout << hand[i].toString() << '\n';
cout << endl;
}
bool Hand::pair() const
{
for (unsigned i = 0; i < faceCount.size(); ++i)
if (faceCount[i] == 2)
return true;
return false;
}
bool Hand::twoPair() const
{
bool foundOne = false;
for (unsigned i = 0; i < faceCount.size(); ++i)
{
if (faceCount[i] == 2 && foundOne)
return true;
else if (faceCount[i] == 2)
foundOne = true;
}
return false;
}
bool Hand::threeOfAKind() const
{
for (unsigned i = 0; i < faceCount.size(); ++i)
if (faceCount[i] == 3)
return true;
return false;
}
bool Hand::fourOfAKind() const
{
for (unsigned i = 0; i < faceCount.size(); ++i)
if (faceCount[i] == 4)
return true;
return false;
}
bool Hand::flush() const
{
int suit = hand[0].getSuit();
for (unsigned i = 1; i < hand.size(); ++i)
if (hand[i].getSuit() != suit)
return false;
return true;
}
bool Hand::straight() const
{
vector< int > tmp = faceCount;
tmp.push_back( tmp[ 0 ] );
if ( tmp[ 0 ] == 1 && tmp[ 1 ] == 1 && tmp[ 2 ] == 1 &&
tmp[ 3 ] == 1 && tmp[ 4 ] == 1 )
return true;
unsigned i = 1;
while ( i < tmp.size() && tmp[ i ] == 0 )
++i;
unsigned start = i;
while ( i < tmp.size() && tmp[ i ] == 1 )
++i;
return i == start + 5;
}
#include <iostream>
#include <iomanip>
#include "DeckOfCards.h"
#include "Hand.h"
using namespace std;
int main()
{
DeckOfCards myDeckOfCards;
myDeckOfCards.shuffle();
Hand hand(myDeckOfCards);
hand.print();
if (hand.fourOfAKind())
cout << "Hand contains four of a kind" << endl;
else if (hand.flush())
cout << "Hand contains a flush" << endl;
else if (hand.straight())
cout << "Hand contains a straight" << endl;
else if (hand.threeOfAKind())
cout << "Hand contains three of a kind" << endl;
else if (hand.twoPair())
cout << "Hand contains two pairs" << endl;
else if (hand.pair())
cout << "Hand contains a pair" << endl;
}