C++大学教程(第七版)课后习题答案第六章

406 阅读3分钟

第六章

6.12(停车费)

int f = 0,i = 1,j = 1;
    while(i<n && j<m){
        while(a[i]<=f) 
            i++;
        while(c[j]<=f) 
            j++;
        if(b[i]<=d[j]) 
        { 
            A<--{i}; 
            f = b[i]; 
            i++;
        }
        else 
        { 
            B<--{j}; 
            f = d[j]; 
            j++;
        }
    }
    if(i==n){
        从Y中选取活动
    }
    if(j==m){
        从X中选取活动
    }
    return A and B;

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double calculateCharges( double ); 

int main()
{
   double hour;
   double currentCharge; 
   double totalCharges = 0.0;
   double totalHours = 0.0;
   bool first = true; 
   cout << fixed;
   cout << "Enter the hours parked for 3 cars: ";
   for ( int i = 1; i <= 3; i++ )
   {
      cin >> hour;
      totalHours += hour; 
      if ( first )
      {
         cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"
            << setw( 15 ) << "Charge\n";
         first = false; // prevent from printing again
      } 
      currentCharge = calculateCharges( hour );
      totalCharges += currentCharge; 
      cout << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour
         << setw( 14 ) << setprecision( 2 ) << currentCharge << "\n";
   } 
   cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )
      << totalHours << setw( 14 ) << setprecision( 2 )
      << totalCharges << endl;
} 

double calculateCharges( double hours )
{
   double charge;
   if ( hours < 3.0 ) 
      charge = 2.0;
   else 
      charge = 2.0 + .5 * ceil( hours - 3.0 );
   return ( charge > 10.0 ? 10.0 : charge );
}

6.13(数的整数舍入)

#include <iostream> 
#include <iomanip> 
#include <cmath>
using namespace std;

double roundToIntegers( double );

int main()
{
   double x; 
   double y; 
   cout << fixed;
   for ( int loop = 1; loop <= 5; loop++ ) 
   {
      cout << "Enter a number: ";
      cin >> x;

      y = roundToIntegers( x ); 
      cout << setprecision( 6 ) << x << " rounded is "
         << setprecision( 1 ) << y << endl;
   }
}

double roundToIntegers( double value )
{
	return floor( value + .5 ); 
}

6.14(数的特定小数舍入)

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double roundToInteger( double ); 
double roundToTenths( double );
double roundToHundredths( double );
double roundToThousandths( double );

int main()
{   
   int count;
   double number;
   cout << "How many numbers do you want to process? " << fixed;
   cin >> count;
   for ( int i = 0; i < count; i++ ) 
   {
      cout << "\nEnter number: ";
      cin >> number;
      cout << setprecision( 6 ) << number 
         << " rounded to the nearest integer is:    "
         << setprecision( 0 ) << roundToInteger( number ) << '\n';
      cout << setprecision( 6 ) << number 
         << " rounded to the nearest tenth is:      "
         << setprecision( 1 ) << roundToTenths( number ) << '\n';
      cout << setprecision( 6 ) << number 
         << " rounded to the nearest hundredth is:  "
         << setprecision( 2 ) << roundToHundredths( number ) << '\n';
      cout << setprecision( 6 ) << number 
         << " rounded to the nearest thousandth is: "
         << setprecision( 3 ) << roundToThousandths( number ) << '\n';
   }
}

double roundToInteger( double n )
{
   return floor( n + .5 );
}

double roundToTenths( double n )
{
   return floor( n * 10 + .5 ) / 10;
} 

double roundToHundredths( double n )
{
   return floor( n * 100 + .5 ) / 100;
}

double roundToThousandths( double n )
{
   return floor( n * 1000 + .5 ) / 1000;
}

6.18(求幂计算)

#include <iostream>
using namespace std;

int integerPower( int, int ); 

int main()
{
   int exp; 
   int base; 
   cout << "Enter base and exponent: ";
   cin >> base >> exp;
   cout << base << " to the power " << exp << " is: "
      << integerPower( base, exp ) << endl;
} 

int integerPower( int b, int e )
{
   int product = 1;
   for ( int i = 1; i <= e; i++ )
      product *= b;
   return product; 
}

6.19(直角三角形斜边的计算)

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double hypotenuse( double, double );

int main()
{
   double side1; 
   double side2;   
   cout << fixed; 
   for ( int i = 1; i <= 3; i++ ) 
   {
      cout << "\nEnter 2 sides of right triangle: ";
      cin >> side1 >> side2;
      cout << "Hypotenuse:  " << setprecision( 1 )
         << hypotenuse( side1, side2 ) << endl;
   } 
} 

double hypotenuse( double s1, double s2 )
{
   return sqrt( s1 * s1 + s2 * s2 );
}

6.20(倍数)

#include <iostream>
using namespace std;

bool multiple( int, int );

int main()
{
   int x;
   int y; 
   for ( int i = 1; i <= 3; i++ ) 
   {
      cout << "Enter two integers: ";
      cin >> x >> y;
      if ( multiple( x, y ) )
         cout << y << " is a multiple of " << x << "\n\n";
      else
         cout << y << " is not a multiple of " << x << "\n\n";
   } 
   cout << endl;
}

bool multiple( int a, int b )
{
   return !( b % a );
}

6.21(偶数)

#include <iostream>
using namespace std;

bool isEven( int );

int main()
{
   int x;
   for ( int i = 1; i <= 3; i++ ) 
   {
      cout << "Enter an integer: ";
      cin >> x;
      if ( isEven( x ) )
         cout << x << " is an even integer\n\n";
      else
         cout << x << " is an odd integer\n\n";
   }   cout << endl;
}

bool isEven( int a )
{
   return !( a % 2 );
}

6.22(星号组成的方形图案)

#include <iostream>
using namespace std;

void square( int );

int main()
{
   int side;

   cout << "Enter side: ";
   cin >> side;
   cout << '\n';

   square( side ); 
   cout << endl;
} 

void square( int side )
{
   for ( int row = 1; row <= side; row++ ) 
   {
      for ( int col = 1; col <= side; col++ )
         cout << '*';
      cout << '\n';
   }
}

6.23(任意符号组成的方形图案)

#include <iostream>
using namespace std;

void square( int, char );

int main()
{
   int side; 
   char character;
   cout << "Enter a character and the side length: ";
   cin >> character >> side;
   cout << '\n';
   square( side, character );
   cout << endl;
}

void square( int side, char fillCharacter )
{
   for ( int row = 1; row <= side; row++ ) 
   {
      for ( int col = 1; col <= side; col++ )
         cout << fillCharacter;
      cout << '\n';
   }
}

6.24(数字分离)

#include <iostream>
using namespace std;

int quotient( int, int ); 
int remainder( int, int );
void printDigits( int ); 

int main()
{
   int number; 
   do
   {
      cout << "Enter an integer between 1 and 32767: ";
      cin >> number;
   } 
   while ( number < 1 || number > 32767 );

   cout << "The digits in the number are:\n";
   printDigits( number );
   cout << endl;
} 

int quotient( int a, int b )
{
   return a / b;
} 

int remainder( int a, int b )
{
   return a % b;
} 

void printDigits( int number )
{
   int divisor = 10000; 
   while ( number < divisor )
      divisor = quotient( divisor, 10 );
   while ( divisor >= 1 )
   {
      cout << quotient( number, divisor ) << "  ";
      number = remainder( number, divisor );
      divisor = quotient( divisor, 10 );
   } 
}

6.25(秒数计算)

#include <iostream>
#include <cmath>
using namespace std;

unsigned seconds( unsigned, unsigned, unsigned ); 

int main()
{
   unsigned hours; 
   unsigned minutes; 
   unsigned secs;
   double first;
   double second; 
   double difference;
   cout << "Enter the first time as three integers: ";
   cin >> hours >> minutes >> secs;
   first = seconds( hours, minutes, secs ); 
   cout << "Enter the second time as three integers: ";
   cin >> hours >> minutes >> secs;
   second = seconds( hours, minutes, secs ); 
   difference = fabs( first - second ); 
   cout << "The difference between the times is "
      << difference << " seconds" << endl;
} 

unsigned seconds( unsigned h, unsigned m, unsigned s )
{
   return 3600 * ( h >= 12 ? h - 12 : h ) + 60 * m + s;
}

6.26(摄氏温度和华氏温度)

#include <iostream>
#include <iomanip>
using namespace std;

int celsius( int );
int fahrenheit( int ); 

int main()
{
   cout << "Fahrenheit equivalents of Celsius temperatures:" << endl;
   for ( int t = 0; t < 4; t++ )
      cout << setw( 7 ) << "Celsius" << setw( 12 ) << "Fahrenheit ";
   cout << endl;
   for ( int i = 0; i < 25; i++ ) 
   {
      for ( int j = 0; j <= 75; j += 25 ) 
         cout << setw( 7 ) << i + j 
            << setw( 11 ) << fahrenheit( i + j ) << ' ';
      cout << endl;
   }
   cout << setw( 64 ) << 100 << setw( 11 ) << fahrenheit( 100 ) << endl;
   cout << "\nCelsius equivalents of Fahrenheit temperatures:" << endl;
   for ( int t = 0; t < 4; t++ )
      cout << setw( 10 ) << "Fahrenheit" << setw( 9 ) << "Celsius ";
   cout << endl;
   for ( int i = 32; i < 77; i++ ) 
   {
      for ( int j = 0; j <= 135; j += 45 ) 
         cout << setw( 10 ) << i + j 
            << setw( 8 ) << celsius( i + j ) << ' ';
      cout << endl;
   } 
   cout << setw( 67 ) << 212 << setw( 8 ) << celsius( 212 ) << endl;
} 

int celsius( int fTemp )
{
   return static_cast< int > ( 5.0 / 9.0 * ( fTemp - 32 ) );
} 

int fahrenheit( int cTemp )
{
   return static_cast< int > ( 9.0 / 5.0 * cTemp + 32 );
}

6.27(找最小数)

#include <iostream> 
using namespace std;

double smallest( double, double, double );

int main()
{
   double x;
   double y;
   double z;
   cout << "Enter three numbers: ";
   cin >> x >> y >> z;
   cout << "The smallest value is " << smallest( x, y, z ) << endl;
} 

double smallest( double a, double b, double c )
{
   if ( a < b && a < c )
      return a;
   else if ( b < a && b < c )
      return b;
   else
      return c;
}

6.28(完数)

#include <iostream>
using namespace std;

bool isPerfect( int ); 
void printSum( int ); 

int main()
{
   cout << "Perfect integers between 1 and 1000:" << endl;
   for ( int j = 2; j <= 1000; j++ )
   {
      if ( isPerfect( j ) ) 
          printSum( j ); 
   } 
   cout << endl;
} 

bool isPerfect( int value )
{
   int factorSum = 1;

   for ( int i = 2; i <= value / 2; i++ )
   {if ( value % i == 0 )
         factorSum += i; 
   } 

   return factorSum == value;
} 

void printSum( int value )
{
   cout << value << " = 1";
   for ( int i = 2; i <= value / 2; i++ )
   {
      if ( value % i == 0 )
         cout << " + " << i; 
   }

   cout << endl;
} 

6.29(素数)

Part a

#include <iostream> 
#include <iomanip> 
using namespace std;

bool isPrime( int ); 

int main()
{
   int count=1;  
   cout <<"The prime numbers from 1 to 10000 are:"<< endl;
   cout <<setw( 6 )<< 2;

   for (int loop=3;loop<10000;loop+=2)
   {
      if (isPrime(loop))
      {
         count++;
         cout <<setw(5)<< loop;
         if (count%10==0)
            cout<<'\n';
      } 
   } 
   cout <<endl<<"Total of "<< count <<"prime numbers between 1 and 10000."<< endl;
} 

bool isPrime(int n)
{

   for (int loop2=2;loop2<=n/2;loop2++)
   {
      if (n%loop2==0)
      return false;
   }
   return true;
} 

Part b

#include <iostream> 
#include <iomanip> 
#include <cmath>
using namespace std;

bool isPrime( int );

int main()
{
   int count = 1;
   cout << "The prime numbers from 1 to 10000 are:" << endl;
   cout << setw( 6 ) << 2; // 2 is only even prime
   for ( int loop = 3; loop < 10000; loop += 2 )
   {
      if ( isPrime( loop ) ) 
      {
         count++;
         cout << setw( 6 ) << loop;
         if ( count % 10 == 0 )
            cout << '\n';
      } 
   }
   cout << endl << "Total of " << count 
      << " prime numbers between 1 and 10000." << endl;
}

bool isPrime( int n )
{
   for ( int i = 2; 
      i <= static_cast< int > ( sqrt( static_cast< double > ( n ) ) );
      i++ )
   {
      if ( n % i == 0 )
         return false;
   } 
   return true;
}

6.30(数字反向)

#include <iostream>
#include <iomanip>
using namespace std;

int reverseDigits( int ); // function prototype

int main()
{
   int number;
   cout << "Enter a number between 1 and 9999: ";
   cin >> number;
   cout << "The number with its digits reversed is: ";
   cout << reverseDigits( number ) << endl;
}

int reverseDigits( int n )
{
   int reverse = 0;  
   while ( n > 0 )
   {
      reverse *= 10; 
      reverse += n % 10; 
      n /= 10; 
   } 
   return reverse;
}

6.31(最大公约数)

#include <iostream>
using namespace std;

int gcd(int,int);

int main()
{
   int a;
   int b; 
   for (int j=1;j!=12342323;j++) 
   {
      cout<<"Enter two integers:";
      cin>>a>>b;
      cout<<"The greatest common divisor of" <<a<<"and"<<b<<"is";
      cout <<gcd(a,b)<<endl;
   } 
} 

int gcd(int x,int y)
{
   int greatest=1;
   for(int i=2;i<=((x<y)?x:y);i++)
   {
      if (x%i==0&&y%i==0)
         greatest = i;
   }
   return 0;
}

6.32(成绩的绩点)

#include <iostream>
using namespace std;

int qualityPoints( int );

int main()
{
   int average; 
   for ( int loop = 1; loop <= 5; loop++ ) 
   {
      cout << "\nEnter the student's average: ";
      cin >> average;
      cout << average << " on a 4 point scale is "
         << qualityPoints( average ) << endl;
   } 
   cout << endl;
}

int qualityPoints( int average )
{
   if ( average >= 90 ) 
      return 4;
   else if ( average >= 80 )
      return 3;
   else if ( average >= 70 )
      return 2;
   else if ( average >= 60 )
      return 1;
   else // 0 <= average < 60
      return 0;
}

6.33(抛硬币)

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int flip();

int main()
{
    int headsCount = 0;
    int tailsCount = 0;
    srand(time(0));
    for (int loop = 1; loop <= 100; loop++)
    {
        if (flip() == 0)
        {
            ++tailsCount;
            cout << "Tails ";
        }
        else
        {
            ++headsCount;
            cout << "Heads ";
        } 
        if (loop % 10 == 0) // 10 tosses per line
            cout << endl;
    } 
    cout << "\nThe total number of Heads was " << headsCount
        << "\nThe total number of Tails was " << tailsCount << endl;
}

int flip()
{
    return rand() % 2; // scale by 2 for binary result
}

6.34(猜数字游戏)

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void guessGame(); 
bool isCorrect( int, int );

int main()
{
   srand( time( 0 ) );
   guessGame();
} 

void guessGame()
{
   int answer;
   int guess;
   char response;
   do 
   {
      answer = 1 + rand() % 1000;
      cout << "I have a number between 1 and 1000.\n" 
         << "Can you guess my number?\n" 
         << "Please type your first guess." << endl << "? ";
      cin >> guess;
      while ( !isCorrect( guess, answer ) ) 
         cin >> guess;  
      cout << "\nExcellent! You guessed the number!\n"
         << "Would you like to play again (y or n)? ";
      cin >> response;
      cout << endl;
   } while ( response == 'y' );
} 

bool isCorrect( int g, int a )
{
   if ( g == a )
      return true;
   if ( g < a )
      cout << "Too low. Try again.\n? ";
   else
      cout << "Too high. Try again.\n? ";
   return false;
}

6.35(猜数字游戏的修改)

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void guessGame();
bool isCorrect( int, int ); 
void analyzeCount( int );

int main()
{
   srand( time( 0 ) );
   guessGame();
} 

void guessGame()
{
   int answer; 
   int guess; 
   int total; 
   char response; 
   do 
   {
      answer = 1 + rand() % 1000;
      total = 0; // clear total
      cout << "I have a number between 1 and 1000.\n" 
         << "Can you guess my number?\n" 
         << "Please type your first guess." << endl << "? ";
      cin >> guess;
      total++;
      while ( !isCorrect( guess, answer ) ) 
      {
         cin >> guess;      
         total++; 
      } 
      cout << "\nExcellent! You guessed the number!\n";
      analyzeCount( total );
      cout << "Would you like to play again (y or n)? ";
      cin >> response;
      cout << endl;
   } while ( response == 'y' );
} 

bool isCorrect( int g, int a )
{
   if ( g == a )
      return true;
   if ( g < a ) 
      cout << "Too low. Try again.\n? ";
   else
      cout << "Too high. Try again.\n? ";
   return false;
} 

void analyzeCount( int count )
{
   if ( count < 10 )
      cout << "Either you know the secret or you got lucky!\n";
   else if ( count == 10 )
      cout << "Ahah! You know the secret!\n";
   else
      cout << "You should be able to do better!\n\n";
}

6.36(递归的求幂计算)

#include <iostream>
using namespace std;

long power( long, long );

int main()
{
   long b; // base 
   long e; // exponent
   cout << "Enter a base and an exponent: ";
   cin >> b >> e;
   cout << b << " raised to the " << e << " is " << power( b, e ) << endl;
} 

long power( long base, long exponent )
{
   if ( exponent == 1 ) 
      return base;
   else 
      return base * power( base, exponent - 1 );
}

6.37(斐波那契数列的迭代版本)

Part a

#include <iostream>
using namespace std;

int fibonacci( int );

int main()
{
   for ( int counter = 0; counter <= 10; counter++ )
      cout << "fibonacci( " << counter << " ) = "
         << fibonacci( counter ) << endl;
   cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;
   cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;
   cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
} 

int fibonacci( int n )
{
   int fib0 = 0;
   int fib1 = 1; 
   int temp;
   if ( n == 0 ) 
      return 0;
   for ( int i = 2; i <= n; i++ ) 
   {
      temp = fib1; 
      fib1 = fib0 + fib1;  
      fib0 = temp; 
   }   return fib1;
}

Part b

#include <iostream>
#include <iomanip>
using namespace std;

double fibonacci( int );

int main()
{
   cout << fixed << setprecision( 1 );
   for ( int counter = 0; counter <= 10; counter++ )
      cout << "fibonacci( " << counter << " ) = "
         << fibonacci( counter ) << endl;
   cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;
   cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;
   cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
} 

double fibonacci( int n )
{
   double fib0 = 0;  
   double fib1 = 1;  
   double temp; 
   if ( n == 0 )
      return 0;
   for ( int i = 2; i <= n; i++ ) 
   {
      temp = fib1;
      fib1 = fib0 + fib1;
      fib0 = temp;
   } 
   return fib1;
}

6.38(汉诺塔问题)

#include <iostream>
using namespace std;

void towers( int, int, int, int );

int main()
{
   int nDisks; 
   cout << "Enter the starting number of disks: ";
   cin >> nDisks;
   towers( nDisks, 1, 3, 2 );
}

void towers( int disks, int start, int end, int temp )
{
   if ( disks == 1 )
      cout << start << " --> " << end << '\n';
   else 
   {
      towers( disks - 1, start, temp, end );
      cout << start << " --> " << end << '\n';
      towers( disks - 1, temp, end, start );
   } 
}

!6.39(汉诺塔问题的迭代版本)

6.40(递归的可视化)

#include <iostream>
#include <iomanip>
using namespace std;

unsigned long factorial( unsigned long ); 

int main()
{
   for ( int i = 0; i <= 10; i++ )
   {
      cout << "Calculating factorial ( " << i << " )" << endl;
      unsigned long result = factorial( i );
      cout << setw( 2 ) << i << "! = " << result << endl << endl;
   }
}

unsigned long factorial( unsigned long number )
{
   if ( number <= 1 ) 
   {
      cout << "   Reached base case of 1" << endl;
      return 1;
   }
   else 
   {
      cout << setw( number * 3 ) << ""
         << "local variable number: " << number << endl;
      cout << setw( number * 3 ) << "" 
         << "recursively calling factorial( " 
         << number - 1 << " )" << endl << endl;
      return ( number * factorial( number - 1 ) );
   } 
}

6.41(递归的最大公约数)

#include <iostream>
using namespace std;

unsigned gcd( unsigned int, unsigned int );

int main()
{
   unsigned x; 
   unsigned y;
   cout << "Enter two integers: ";
   cin >> x >> y;
   cout << "Greatest common divisor of " << x << " and "
      << y << " is " << gcd( x, y ) << endl;
} 

unsigned gcd( unsigned a, unsigned b )
{
   if ( b == 0 )
      return a;
   else // recursion step
      return gcd( b, a % b );
}

6.42(两点之间的距离)

#include <iostream>
#include <cmath>
using namespace std;

double distance(double, double, double, double);

int main()
{
	cout << "Enter two point:";
	double a, b, c, d;
	cin >> a >> b >> c >> d;
	cout << "The distance of the point( " << a << " , " << b << " ) and point ( "
		<< c << " , " << d << " ) is " << distance(a, b, c, d) << " .";
}

double distance(double a, double b, double c, double d) {
	double s = (c-a) * (c-a) + (d-b) * (d-b);
	return sqrt((c - a) * (c - a) + (d - b) * (d - b));
}

6.43(修改6.45)

#include <iostream>
using namespace std;

int mystery( int, int ); // function prototype

int main()
{
   int x; // first integer
   int y; // second integer

   cout << "Enter two integers: ";
   cin >> x >> y;
   cout << "The result is " << mystery( x, y ) << endl;
} // end main

// mystery multiplies a * b using recursion
int mystery( int a, int b )
{
   if ( b < 0 ) // if b is negative
   {
      // multiply both a and b by -1, so b is positive
      // note this multiplies answer by (-1)*(-1) = 1
      a *= -1;
      b *= -1;
   } // end if

   if ( b == 1 ) // base case
      return a;
   else // recursion step
      return a + mystery( a, b - 1 );
}

6.48(掷双骰子游戏的改进)

#include <iostream>
#include <cstdlib> 
#include <ctime>
using namespace std;

enum Status { WON, LOST, CONTINUE };

int rollDice( void );
Status craps( void ); 
void chatter( void );

int main()
{
   Status result;
   int wager = 0;
   int bankBalance = 1000;
   char playAgain;
   srand( time( 0 ) );
   do 
   {
      cout << "You have $" << bankBalance 
         << " in the bank.\nPlace your wager: ";
      cin >> wager;
      while ( wager <= 0 || wager > bankBalance ) 
      {
         cout << "Please bet a valid amount.\n";
         cin >> wager;
      } 
      result = craps();
      if ( result == LOST ) 
      {
         bankBalance -= wager;
         cout << "Your new bank balance is $" << bankBalance << "\n";
         if ( bankBalance == 0 )
         {
            cout << "Sorry. You Busted! Thank You For Playing.\n";
            break;
         } 
      } 
      else 
      {
         bankBalance += wager; 
         cout << "Your new bank balance is $" << bankBalance << "\n";
      } 
      cout << "Would you like to try your luck again (y/n)? ";
      cin >> playAgain;

   } while ( playAgain == 'y' || playAgain == 'Y' );
   cout << endl;
} 

int rollDice( void )
{
   int die1; 
   int die2; 
   int workSum;
   die1 = 1 + rand() % 6;
   die2 = 1 + rand() % 6; 
   workSum = die1 + die2; 
   cout << "Player rolled " << die1 << " + " << die2
      << " = " << workSum << endl;
   return workSum;
} 

Status craps( void )
{
   int sum;
   int myPoint;
   Status gameStatus;
   sum = rollDice();
   switch ( sum ) 
   {
      case 7:
      case 11:
         gameStatus = WON;
         break;
      case 2:
      case 3: 
      case 12:
         gameStatus = LOST;
         break;
      default:
         gameStatus = CONTINUE;
         myPoint = sum;
         cout << "Point is " << myPoint << '\n';
         break;
   } 
   while ( gameStatus == CONTINUE ) 
   {
      chatter(); 
      sum = rollDice();
      if ( sum == myPoint )
         gameStatus = WON;
      else 
      {
         if ( sum == 7 )
            gameStatus = LOST;
      }
   }
   if ( gameStatus == WON ) 
   {
      cout << "Player wins" << endl;
      return WON;
   }
   else 
   {
      cout << "Player loses" << endl;
      return LOST;
   }
}

void chatter()
{
   switch ( rand() % 9 ) 
   {
      case 0:
         cout << "Oh, you're going for broke, huh?";
         break;
      case 1:
         cout << "Aw cmon, take a chance!";
         break;
      case 2:
         cout << "Hey, I think this guy is going to break the bank!!";
         break;
      case 3:
         cout << "You're up big. Now's the time to cash in your chips!";
         break;
      case 4:
         cout << "Way too lucky! Those dice have to be loaded!";
         break;
      case 5:
         cout << "Bet it all! Bet it all!";
         break;
      case 6:
         cout << "Can I borrow a chip?";
         break;
      case 7:
         cout << "Let's try our luck at another table.";
         break;
      case 8:
         cout << "You're a cheat! It is just a matter of time"
            << "\nbefore I catch you!!!";
         break;
   } 
   cout << endl;
}

6.49(圆面积计算)

#include <iostream>
using namespace std;

double pi = 3.14159; 

inline double circleArea( double r ) 
{ 
   return pi * r * r;
} 

int main()
{
   double radius; 
   cout << "Enter the radius of the circle: ";
   cin >> radius;
   cout << "The area of the circle is " << circleArea( radius ) << endl;
}

6.52(函数模板minimum)

#include <iostream>
using namespace std;

template < class T >
T minimum( T value1, T value2 )   
{
   if ( value1 < value2 )
      return value1;
   else
      return value2;
}

int main()
{
   int int1;
   int int2; 
   cout << "Input two integer values: ";
   cin >> int1 >> int2;
   cout << "The smaller integer value is: " << minimum( int1, int2 );
   char char1;
   char char2;
   cout << "\n\nInput two characters: ";
   cin >> char1 >> char2;
   cout << "The smaller character value is: " << minimum( char1, char2 );
   double double1; 
   double double2; 
   cout << "\n\nInput two double values: ";
   cin >> double1 >> double2;
   cout << "The smaller double value is: " << minimum( double1, double2 ) << endl;
}

6.53(函数模板maximum)

#include <iostream>
using namespace std;

template < class T >
T maximum(T value1, T value2)
{
    if (value1 > value2)
        return value1;
    else
        return value2;
} 

int main()
{
    int int1;
    int int2;
    cout << "Input two integer values: ";
    cin >> int1 >> int2;
    cout << "The larger integer value is: " << maximum(int1, int2);
    char char1;
    char char2;
    cout << "\n\nInput two characters: ";
    cin >> char1 >> char2;
    cout << "The larger character value is: " << maximum(char1, char2);
    double double1; // first double value
    double double2; // second double value
    cout << "\n\nInput two double values: ";
    cin >> double1 >> double2;
    cout << "The larger double value is: " << maximum(double1, double2) << endl;
}

6.55(C++11的作用域限定的枚举类型)

#include <iostream> 
#include <cstdlib>
#include <ctime>
using namespace std;

int generateProblem();

int main()
{
   int response = 0;
   srand( time( 0 ) );
   while ( response != -1 ) 
   {
      int answer = generateProblem();
      cin >> response; 
      while ( response != -1 && response != answer ) 
      {
         cout << "No. Please try again." << endl << "? ";
         cin >> response;
      }
      if ( response == answer )
         cout << "Very good!" << endl << endl;
   }
   cout << "That's all for now. Bye." << endl;
} 

int generateProblem()
{
   int x = rand() % 10;
   int y = rand() % 10;
   cout << "How much is " << x << " times " << y << " (-1 to End)\n? ";
   return x * y; // return product
}