C++大学教程(第七版)课后习题答案第二三四五章

829 阅读4分钟

第二章

2.16(算术运算)

#include<iostream>
using namespace std;

int main() {
	cout << "Enter two numbers: ";
	int a, b;
	cin >> a >> b;
	cout << a + b << ' ' << a * b << ' ' << a - b << ' ' << a / b;
}

2.17(输出)

#include<iostream>
using namespace std;

int main() {
	cout << "1 2 3 4";
	cout << endl;
	cout << "1 " << "2 " << "3 " << "4 ";
	cout << endl;
	cout << "1 ";
	cout << "2 ";
	cout << "3 ";
	cout << "4 ";
}

2.18(整数比较)

#include<iostream>
using namespace std;

int main()
{
	cout << "Enter two numbers: ";
	double a, b;
	cin >> a >> b;
	if (a == b)
		cout << "These numbers are equal.";
	else
		cout << (a > b ? a : b) << " is large.";
}

2.19(算术运算、求最大和最小数)

#include<iostream>
using namespace std;

int main()
{
	cout << "Input three different integers: ";
	int a, b, c, largest, smallest;
	cin >> a >> b >> c;
	largest = a;
	smallest = a;
	if (b > largest)
		largest = b;
	if (c > largest)
		largest = c;
	if(smallest>b)
		smallest = b;
	if(smallest > c)
		smallest = c;
	cout << "Sum is: " << a + b + c << endl
		<< "Average is: " << (a + b + c) / 3 << endl
		<< "Product is: " << a * b * c << endl
		<< "Smallest is: " << smallest << endl
		<< "Largest is: " << largest << endl;
}

2.20(圆的直径、周长和面积)

#include<iostream>
using namespace std;

int main()
{
	cout << "Enter the radius of the circle: ";
	double radius;
	const double pi = 3.14159;
	cin >> radius;
	cout << "The diameter of the circle is " << 2 * radius << endl
		<< "The perimeter of the circle is " << 2 * radius * pi<<endl
		<< "The area of the circle is " << radius * radius * pi;

}

2.21(用星号显示图形)

#include<iostream>
using namespace std;

int main()
{
	//first
	for (int i = 0; i < 9; i++)
		cout << '*';
	cout << endl;
	for (int i = 0; i < 7; i++)
	{
		cout << '*';
		for (int j = 0; j < 7; j++)
			cout << ' ';
		cout << '*' << endl;
	}
	for (int i = 0; i < 9; i++)
		cout << '*';
	cout << endl;

	//second
	cout << "   ***   " << endl;
	cout << " *     * " << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << '*';
		for (int j = 0; j < 7; j++)
			cout << ' ';
		cout << '*' << endl;
	}
	cout << " *     * " << endl;
	cout << "   ***   " << endl;

	//third
	for (int i = 0; i<3; i++) {
		for (int j = 0; j < 2-i; j++)
			cout << " ";
		for (int k = 0; k < 2 * i + 1; k++)
			cout << "*";
		cout << endl;
	}
	for (int i = 0; i < 6; i++)
	{
		for (int j = 0; j < 2;j++)
			cout << " ";
		cout << "*" << endl;
	}
        
	//fourth
	cout << "    *" << endl;
	for (int i = 1; i < 5; i++) {
		for (int j = 1; j < 5 - i; j++)
			cout << " ";
		cout << "*";
		for (int j = 1; j < 2 * i; j++)
			cout << " ";
		cout << "*" << endl;
	}
	for (int i = 1; i < 4; i++) {
		for (int j = 0; j < i; j++)
			cout << " ";
		cout << "*";
		for (int j = 1; j < 8-2 * i; j++)
			cout << " ";
		cout << "*" << endl;
	}
	cout << "    *";
}

image.png

2.23(最大和最小整数)

#include <iostream>
using namespace std;

int main()
{
	cout << "Enter five integers:";
	int max=0, min=0;
	int a;
	for (int i = 0; i < 5; i++) {
		cin >> a;
		if (a > max)
			max = a;
		else
			if (a < min)
				min = a;
	}
	cout << "The max is " << max << " and the min is " << min << ".";
}

2.24(奇数和偶数)

#include <iostream>
using namespace std;

int main()
{
	cout << "Enter an integers:";
	int a;
	cin >> a;
	a % 2 ? cout << a << " 为偶数" : cout << a << " 为奇数" << endl;
}

2.25(倍数)

#include <iostream>
using namespace std;

int main()
{
	cout << "Enter two integers:";
	int a, b;
	cin >> a >> b;
	if(a<b)
		cout<< a << " 不是 " << b << " 的倍数。";
	else
		cout << a << (a % b ? " 不是 " : " 是 ") << b << " 的倍数。";
}

2.26(棋盘图案)

#include <iostream>
using namespace std;

int main()
{
	for (int i = 0; i < 8; i++)
	{
		if (i % 2 == 0) {
			for (int j = 0; j < 8; j++)
				cout << "* ";
			cout << endl;
		}
		else{
			for (int j = 0; j < 8; j++)
				cout << " *";
			cout << endl;
		}
	}
}

2.27(字符的等价整数值)

#include <iostream>
using namespace std;

int main()
{
	cout << "Enter an integer:";
	int a;
	cin >> a;
	cout << static_cast<char>(a);
}

2.28(整数的各位数字)

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter a five-digit number:";
    int a;
    cin >> a;
    short m[5];
    for (int i = 0; i < 5; i++)
    {
        m[i] = a % 10;
        a /= 10;
    }
    for (int i = 4; i >=0 ; i--)
        cout << m[i] << "   ";
}

2.29(表格)

#include <iostream>
using namespace std;

int main()
{
    cout << "integer\tsquare\tclub" << endl;
    for (int i = 0; i < 11; i++)
    {
        cout << i<<'\t' << i * i <<'\t' << i * i * i << endl;
    }
}

第三章

3.11(修改GradeBook类)

//GradeBook.h
#include <string>

class GradeBook
{
public:
    explicit GradeBook(std::string, std::string);
    void setCourseName(std::string);
    std::string getCourseName() const;
    void setTeacherName(std::string);
    std::string getTeacherName() const;
    void displayMessage() const;
private:
    std::string courseName;
    std::string teacherName;
};
//GradeBook.cpp
#include <iostream>
#include "GradeBook.h"
using namespace std;

GradeBook::GradeBook(string name1,string name2)
    :courseName(name1),teacherName(name2)
{
}

void GradeBook::setCourseName(string name1) {
    courseName = name1;
}

string GradeBook::getCourseName() const {
    return courseName;
}

void GradeBook::setTeacherName(string name2) {
    courseName = name2;
}

string GradeBook::getTeacherName() const {
    return teacherName;
}
void GradeBook::displayMessage() const {
    cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl
        << "This course is presented by:\n" << getTeacherName() << "!" << endl;
}

3.12(Account类)

//Account.h

class Account
{
public:
    explicit Account(int);
    void credit(int);
    void debit(int);
    int getBalance() const;
private:
    int balance;
};
//GradeBook.cpp

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

Account::Account(int customerBalance)
    :balance(customerBalance)
{
    if (balance < 0) {
        cerr << "Invalid balance";
        balance = 0;
    }
}

void Account::credit(int addBalance) {
    balance += addBalance;
}

void Account::debit(int delBalance) {
    if (balance < delBalance)
        cout << "Debit amount exceeded account balance.";
    else
        balance -= delBalance;
}

int Account::getBalance() const {
    return balance;
}

3.13(Invoice类)

//Invoice.h
#include <string>

class Invoice
{
public:
    explicit Invoice(std::string,std::string,int,int);
    std::string getNumber() const;
    void setNumber(std::string);
    std::string getDescription() const;
    void setDescription(std::string);
    int getSold() const;
    void setSold(int);
    int getPrice() const;
    void setPrice(int);
    int getInvoiceAmount();

private:
    std::string number;
    std::string description;
    int sold;
    int price;
};
//Invoice.cpp
#include <iostream>
#include "Invoice.h"
using namespace std;

Invoice::Invoice(std::string num, std::string desc, int unitSold, int unitPrice)
    :number(num),
    description(desc),
    sold(unitSold),
    price(unitPrice)
{
}

std::string Invoice::getNumber() const {
    return number;
}

void Invoice::setNumber(std::string num) {
    number = num;
}

std::string Invoice::getDescription() const {
    return description;
}

void Invoice::setDescription(std::string desc) {
    description=desc;
}

int Invoice::getSold() const {
    return sold;
}

void Invoice::setSold(int unitSold) {
    if (sold < 0) {
        sold = 0;
    }
    else
        sold = unitSold;
}

int Invoice::Invoice::getPrice() const {
    return price;
}

void Invoice::setPrice(int unitPrice) {
    if (price < 0) {
        price = 0;
    }
    else
        price = unitPrice;
}

int Invoice::getInvoiceAmount() {
    return sold * price;
}

3.14(Emplyee类)

//Employee.h
#include <string>

class Employee {
public:
    explicit Employee(std::string, std::string, int);
    std::string getFName() const;
    void setFName(std::string);
    std::string getLName() const;
    void setLName(std::string);
    int getSalary() const;
    void setSalary(int);
    void displayInformation() const;
private:
    std::string fName;
    std::string lName;
    int salary;
};
//Employee.cpp
#include <iostream>
#include "Employee.h"
using namespace std;

Employee::Employee(std::string firstName, std::string lastName, int psalary)
    :fName(firstName),
    lName(lastName),
    salary(psalary)
{
}

std::string Employee::getFName() const {
    return fName;
}

void Employee::setFName(std::string firstName) {
    fName = firstName;
}

std::string Employee::getLName() const {
    return lName;
}

void Employee::setLName(std::string lastName) {
    fName = lastName;
}

int Employee::getSalary() const {
    return salary;
}
void Employee::setSalary(int psalary) {
    if (psalary < 0) {
        salary = 0;
    }
    else
        salary=psalary;
}
void Employee::displayInformation() const {
    cout << "The first name is " << getFName()<<endl
        << " and the last name is " << getLName()<<endl
        << " and the salary is " << getSalary()<<endl;
}
//main.cpp
#include <iostream>
#include "Employee.cpp"
using namespace std;

int main() {
    Employee e1("Aurora","Geng",300000);
    Employee e2("Paul", "Tang", 500000);
    e1.displayInformation();
    e2.displayInformation();
    e1.setSalary(1.1*300000);
    e2.setSalary(1.1*500000);
    e1.displayInformation();
    e2.displayInformation();
}

3.16(Date类)

//Date.h
#include <string>

class Date {
public:
    explicit Date(unsigned int, unsigned int, unsigned int);
    unsigned int getYear() const;
    void setYear(unsigned int);
    unsigned int getMonth() const;
    void setMonth(unsigned int);
    unsigned int getDay() const;
    void setDay(unsigned int);
    void displayDate() const;
private:
    unsigned int year;
    unsigned int month;
    unsigned int day;
};
//Employee.cpp
#include <iostream>
#include "Date.h"
using namespace std;

Date::Date(unsigned int yr, unsigned int mh, unsigned int dy)
    :year(yr),
    month(mh),
    day(dy)
{
}

unsigned int Date::getYear() const {
    return year;
}

void Date::setYear(unsigned int yr) {
    year = yr;
}

unsigned int Date::getMonth() const {
    return month;
}

void Date::setMonth(unsigned int mh) {
    if (mh < 0) {
        month = 0;
    }
    else
        month=mh;
}

unsigned int Date::getDay() const {
    return day;
}

void Date::setDay(unsigned int dy) {
    day = dy;
}

void Date::displayDate() const {
    cout << "The date is " 
        <<getYear()<<'/'
        <<getMonth()<<'/'
        <<getDay()<<endl;
}
//main.cpp
#include <iostream>
#include "Date.cpp"
using namespace std;

int main() {
    Date date(2021,4,14);
    date.displayDate();
}

第四章

4.13(汽油哩数)

#include <iostream>
using namespace std;

int main()
{
   double gallons; 
   double miles;
   double totalGallons = 0;
   double totalMiles = 0;
   double milesPerGallon;
   double totalMilesPerGallon;
   cout << "Enter miles driven (-1 to quit): ";
   cin >> miles;
   cout << fixed;
   while ( miles != -1 )
   {
      cout << "Enter gallons used: ";
      cin >> gallons;
      totalMiles += miles;
      totalGallons += gallons;
      if ( gallons != 0 )
      {
         milesPerGallon =  miles / gallons;
         cout << "MPG this tankful: " << milesPerGallon;            
      }
      if ( totalGallons != 0 )
      {
         totalMilesPerGallon = totalMiles / totalGallons;
         cout << "\nTotal MPG: " << totalMilesPerGallon;
      }
      cout << "\n\nEnter miles driven (-1 to quit): ";
      cin >> miles;
   }     
}
#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std;

int main()
{
   int account;
   double balance;
   double charges;
   double credits;
   double creditLimit;
   cout << "Enter account number (or -1 to quit): ";
   cin >> account;
   cout << fixed << setprecision( 2 );
   while ( account != -1 )
   {
      cout << "Enter beginning balance: ";
      cin >> balance;
      cout << "Enter total charges: ";
      cin >> charges;
      cout << "Enter total credits: ";
      cin >> credits;
      cout << "Enter credit limit: ";
      cin >> creditLimit;
      balance = balance + charges - credits;
      cout << "New balance is " << balance;
      if ( balance > creditLimit )
         cout << "\nAccount:      " << account
            << "\nCredit limit: " << creditLimit 
            << "\nBalance:      " << balance 
            << "\nCredit Limit Exceeded.";
      cout << "\n\nEnter account number (or -1 to quit): ";
      cin >> account;
   }
}

4.15(销售佣金计算器)

#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std; 

int main()
{
   double sales;
   double wage;
   cout << "Enter sales in dollars (-1 to end): ";
   cin >> sales;
   cout << fixed << setprecision( 2 );
   while ( sales != -1.0 ) 
   {    
      wage = 200.0 + 0.09 * sales; 
      cout << "Salary is: $" << wage;
      cout << "\n\nEnter sales in dollars (-1 to end): ";
      cin >> sales;
   }
} 

4.16(薪金计算器)

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

int main()
{
   double hours;
   double rate;
   double salary;
   cout << "Enter hours worked (-1 to end): ";
   cin >> hours;
   cout << fixed << setprecision( 2 );
   while ( hours != -1.0 ) 
   {
      cout << "Enter hourly rate of the employee ($00.00): ";
      cin >> rate;
      if ( hours <= 40 )
         salary = hours * rate;
      else
         salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5;
      cout << "Salary is $" << salary;
      cout << "\n\nEnter hours worked (-1 to end): ";
      cin >> hours;
   }
}

4.17(找最大数)

#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std; 

int main()
{
   int counter = 0; 
   int largest; 
   cout << "Enter the first number: "; 
   cin >> largest; 
   while ( ++counter < 10 ) // loop 10 times
   {
      cout << "Enter the next number : ";
      cin >> number; 
      if ( number > largest )
         largest = number;
   }    
   cout << "Largest is " << largest << endl; 
}

4.18(表格输出)

#include <iostream>
using namespace std;

int main()
{
   int n = 0;
   cout << "N\t10*N\t100*N\t1000*N\n\n";
   while ( ++n <= 5 ) 
   {
      cout << n << '\t' << 10 * n << '\t' << 100 * n
         << '\t' << 1000 * n << '\n';
   }
   cout << endl;
}

4.19(找最大的两个数)

#include <iostream>
using namespace std; 

int main()
{
   int counter = 0;
   int number; 
   int largest;
   int secondLargest;
   cout << "Enter the first number: "; 
   cin >> largest; 
   cout << "Enter next number: ";
   cin >> number; 
   if ( number > largest )
   {
      secondLargest = largest;
      largest = number;
   } 
   else
      secondLargest = number;
   counter = 2; 
   while ( counter < 10 ) 
   {
      cout << "Enter next number: "; // prompt for next number
      cin >> number; 
      if ( number > largest ) 
      {
         secondLargest = largest;
         largest = number;
      } 
      else if ( number > secondLargest )
         secondLargest = number;
      counter++; // increment counter
   } 
   cout << "\nLargest is " <<  largest 
      << "\nSecond largest is " << secondLargest << endl;
}

4.20(确认用户输入的有效性)

#include <iostream>
using namespace std;

int main()
{
   int passes = 0; 
   int failures = 0;
   int studentCounter = 1;
   int result; 
   while ( studentCounter <= 10 )
   {
      cout << "Enter result (1 = pass, 2 = fail): ";
      cin >> result;
      if ( result == 1 ) 
      {
         passes = passes + 1; 
         studentCounter = studentCounter + 1; 
      } 
      else if ( result == 2 )
      {
         failures = failures + 1; 
         studentCounter = studentCounter + 1; 
      } 
      else 
      {
         cout << "Invalid input" << endl;
      } 
   } 
   cout << "Passed " << passes << "\nFailed " << failures << endl;
   if ( passes > 8 )
      cout << "Bonus to instructor!" << endl;
}

4.25(星号正方形)

#include <iostream>
using namespace std; 

int main()
{
   int stars;
   int column; 
   int row = 1;
   cout << "Enter length of side:";
   cin >> stars;
   if ( stars < 1 )
   {
      stars = 1;
      cout << "Invalid Input\nUsing default value 1\n";
   } 
   else if ( stars > 20 )
   {
      stars = 20;
      cout << "Invalid Input\nUsing default value 20\n";
   }
   while ( row <= stars )
   {
      column = 1;
      while ( column <= stars )
      {
         if ( row == 1 )
            cout << "*";
         else if ( row == stars )
            cout << "*";
         else if ( column == 1 )
            cout << "*";
         else if ( column == stars )
            cout << "*";
         else
            cout << " ";
         column++;
      } 
      cout << endl;
      row++; 
   }
}

4.26(回文)

#include <iostream>
using namespace std; 

int main()
{
   int number = 0;
   int digit1; 
   int digit2;
   int digit4;
   int digit5; 
   int digits = 0; 
   while ( digits != 5 )
   {
      cout << "Enter a 5-digit number: "; 
      cin >> number;
      if ( number < 100000 )
      {
         if ( number > 9999 )
            digits = 5;
         else
            cout << "Number must be 5 digits" << endl;
      } 
      else
         cout << "Number must be 5 digits" << endl;
   } 
   digit1 = number / 10000;
   digit2 = number % 10000 / 1000;
   digit4 = number % 10000 % 1000 % 100 / 10;
   digit5 = number % 10000 % 1000 % 100 % 10;
   if ( digit1 == digit5 )
   {
      if ( digit2 == digit4 )
         cout << number << " is a palindrome!!!" << endl;
      else
         cout << number << " is not a palindrome." << endl;
   }
   else
      cout << number << " is not a palindrome." << endl;
}

4.27(打印二进制数的十进制值)

#include <iostream>
using namespace std; 

int main()
{
   int binary; // binary value
   int bit = 1; // bit positional value
   int decimal = 0; // decimal value
   cout << "Enter a binary number: ";
   cin >> binary;
   while ( binary != 0 )
   {
      decimal += binary % 10 * bit;
      binary /= 10;
      bit *= 2;
   } 
   cout << "Decimal is: " << decimal << endl;
}

4.28(星号棋盘式图案)

#include <iostream>
using namespace std;

int main()
{
   int row = 8; // row counter 
   int side; // side counter
   while ( row-- > 0 ) 
   {
      side = 8; // reset side counter
      if ( row % 2 == 0 )
         cout << ' ';
      while ( side-- > 0 )
         cout << "* ";
      cout << endl;
   } 
}

4.29(无线循环2的倍数)

#include <iostream>
using namespace std;

int main()
{
   int x = 1;
   while ( true ) 
   {
      x *= 2;
      cout << x << endl;
   } 
}

4.30(计算圆的直径、周长和面积)

#include <iostream>
using namespace std; 

int main()
{
   double radius; 
   double pi = 3.14159; 
   cout << "Enter the radius: ";
   cin >> radius;
   cout << "The diameter is " << radius * 2.0;
   cout << "\nThe circumference is " << 2.0 * pi * radius;
   cout << "\nThe area is " << pi * radius * radius << endl;
}

4.32(三角形的边)

include <iostream>
using namespace std; 

int main()
{
   double side1;
   double side2; 
   double side3; 
   bool isTriangle = false; 
   cout << "Enter side 1: ";
   cin >> side1;
   cout << "Enter side 2: ";
   cin >> side2;
   cout << "Enter side 3: ";
   cin >> side3;
   if ( side1 + side2 > side3 )
   {
      if ( side2 + side3 > side1 )
      {
         if ( side3 + side1 > side2 )
            isTriangle = true;
      } 
   } 
   if ( isTriangle )
      cout << "These could be sides to a triangle." << endl;
   else 
      cout << "These do not form a triangle." << endl;
}

4.33(直角三角形的边)

#include <iostream>
using namespace std; 

int main()
{
   int side1;
   int side2; 
   int side3;
   bool isRightTriangle = false;
   cout << "Enter side 1: ";
   cin >> side1;
   cout << "Enter side 2: ";
   cin >> side2;
   cout << "Enter side 3: ";
   cin >> side3;
   int side1Square = side1 * side1;
   int side2Square = side2 * side2;
   int side3Square = side3 * side3;
   if ( ( side1Square + side2Square ) == side3Square )
     isRightTriangle = true;
   else if ( ( side1Square + side3Square ) == side2Square )
      isRightTriangle = true;
   else if ( ( side2Square + side3Square ) == side1Square )
      isRightTriangle = true;
   if ( isRightTriangle )
      cout << "These are the sides of a right triangle." << endl;
   else 
      cout << "These do not form a right triangle." << endl;    
}

4.34(阶乘)

Part a

#include <iostream>
using namespace std; 

int main()
{
   int number; // user input
   int factorial = 1; /
   cout << "Enter a positive Integer: ";
   cin >> number;
   cout << number << "! is ";
   while ( number > 0 ) // calculate factorial
   {
      factorial *= number;
      number--;
   }    
   cout << factorial << endl;
}

Part b

#include <iostream>
using namespace std; 

int main()
{
   int number = 1;
   int accuracy; 
   int factorial = 1;
   double e = 1.0; 
   cout << "Enter desired accuracy of e: ";
   cin >> accuracy;
   while ( number < accuracy )
   {
      factorial *= number;
      e += 1.0 / factorial;
      number++;
   }   
   cout << "e is " << e << endl;
}

Part c

#include <iostream>
using namespace std; 

int main()
{
   int number = 1;
   int accuracy; 
   int factorial = 1; 
   double e = 1.0; 
   double exponent = 1.0;   cout << "Enter exponent: ";
   cin >> x;
   cout << "Enter desired accuracy of e: ";
   cin >> accuracy;
   while ( number < accuracy )
   {
      exponent *= x; 
      factorial *= number; 
      e += exponent / factorial; 
      number++;
   } 
   cout << "e to the " << x << " is " << e << endl;
} 

第五章

5.5(整数求和)

#include <iostream>
using namespace std;

int main()
{
   int total = 0; 
   int number;
   int value;
   cout << "Enter the number of values to be summed " 
      << "followed by the values: \n";
   cin >> number;
   for ( int i = 1; i <= number; i++ ) 
   {
      cin >> value;
      total += value;
   } 
   cout << "Sum of the " << number << " values is " << total << endl;
}

5.6(整数求平均值)

#include <iostream>
using namespace std; 

int main()
{
   int value; 
   int count = 0; 
   int total = 0; 
   cout << "Enter integers (9999 to end):" << endl;
   cin >> value;
   while ( value != 9999 )
   {
      total += value; // update sum
      count++; // update number of inputs
      cin >> value; // read in next value
   } 
   if ( count != 0 )
      cout << "\nThe average is: "
         << static_cast< double > ( total ) / count << endl;
   else
      cout << "\nNo values were entered." << endl;
}

5.8(找最小整数)

#include <iostream>
using namespace std; 

int main()
{
   int number;
   int value;
   int smallest;
   cout << "Enter the number of integers to be processed ";
   cout << "followed by the integers: " << endl;
   cin >> number >> smallest;
   for ( int i = 2; i <= number; i++ ) 
   {
      cin >> value; 
      if ( value < smallest )
         smallest = value;
   } 
   cout << "\nThe smallest integer is: " << smallest << endl;
}

5.9(奇整数的乘积)

#include <iostream>
using namespace std;

int main()
{
   int product = 1;
   for ( int i = 3; i <= 15; i += 2 )
      product *= i;
   cout << "Product of the odd integers from 1 to 15 is: "
      << product << endl;
}

5.10(阶乘)

#include <iostream>
using namespace std;

int main()
{
   int factorial = 1; 
   cout << "x\tx!\n";
   for ( int i = 1; i <= 5; i++ )
   {
      factorial *= i // i!
      cout << i << '\t' << factorial << '\n';
   } 
   cout << endl;
}

5.11(复利)

#include <iostream> 
#include <iomanip> 
#include <cmath> // math functions
using namespace std;

int main()
{
   double amount; 
   double principal = 1000.0;
   cout << fixed << setprecision( 2 );
   for ( int rate = 5; rate <= 10; rate++ ) 
   {
      cout << "Interest Rate: " << rate << "%" 
         << "\nYear\tAmount on deposit\n";
      for ( int year = 1; year <= 10; year++ ) 
      {
         amount = principal * pow( 1 + ( rate / 100.0 ), year );
         cout << year << '\t' << amount << '\n';
      } 
      cout << '\n';
   }
   cout << endl;
}

5.12(使用嵌套的for循环绘制图案)

#include <iostream>
using namespace std; 

int main()
{
   int row; 
   int column; 
   int space; 
   for ( row = 1; row <= 10; row++ )
   {
      for ( column = 1; column <= row; column++ )
         cout << "*";
      cout << endl;
   } 
   cout << endl;
   for ( row = 10; row >= 1; row-- )
   {
      for ( column = 1; column <= row; column++ )
         cout << "*";

      cout << endl;
   } 
   cout << endl;
   for ( row = 10; row >= 1; row-- )
   {
      for ( space = 10; space > row; space-- )
         cout << " ";

      for ( column = 1; column <= row; column++ )
         cout << "*";
      cout << endl;
   } 
   cout << endl;
   for ( row = 10; row >= 1; row-- ) 
   {
      for ( space = 1; space < row; space++ )
         cout << " ";
      for ( column = 10; column >= row; column-- )
         cout << "*";
      cout << endl;
   } 
}

5.13(条形图)

#include <iostream>
using namespace std; 

int main()
{
   int number; 
   cout << "Enter 5 numbers between 1 and 30: ";
   for ( int i = 1; i <= 5; i++ ) 
   {
      cin >> number; 
      for ( int j = 1; j <= number; j++ )
         cout << '*';
      cout << endl;
   } 
   cout << endl;
}

5.14(计算总销售量)

#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std; 

int main()
{
   double product1 = 0; 
   double product2 = 0;
   double product3 = 0;
   double product4 = 0;
   double product5 = 0;
   int productId = 1; 
   int quantity; 
   cout << fixed << setprecision( 2 );
   while ( productId != -1 )
   {
      // determine the product chosen
      cout << "Enter product number (1-5) (-1 to stop): ";
      cin >> productId;
      if ( productId >= 1 && productId <= 5 )
      {
         cout << "Enter quantity sold: ";
         cin >> quantity;
         switch ( productId )
         {
            case 1:
               product1 += quantity * 2.98;
               break;
            case 2:
               product2 += quantity * 4.50;
               break;
            case 3:
               product3 += quantity * 9.98;
               break;
            case 4:
               product4 += quantity * 4.49;
               break;
            case 5:
               product5 += quantity * 6.87;
               break;
         } 
      } 
      else if ( productId != -1 )
         cout << "Product number must be between 1 and 5 or -1 to stop" ;
   } 
   cout << endl;
   cout << "Product 1: $" << product1 << endl;
   cout << "Product 2: $" << product2 << endl;
   cout << "Product 3: $" << product3 << endl;
   cout << "Product 4: $" << product4 << endl;
   cout << "Product 5: $" << product5 << endl;
   cout << "total: $" 
      << product1 + product2 + product3 + product4 + product5 << endl;
}

5.15(修改GradeBook类)

//GradeBook.h
#include <string>
using namespace std;

class GradeBook
{
public:
   GradeBook( string ); 
   void setCourseName( string );
   string getCourseName();
   void displayMessage(); 
   void inputGrades(); 
   void displayGradeReport();
private:
   string courseName; 
   int bCount; 
   int cCount; 
   int dCount; 
   int fCount; 
};
//GradeBook.cpp
#include <iostream>
#include <iomanip> // parameterized stream manipulators
#include "GradeBook.h"
using namespace std;

GradeBook::GradeBook( string name )
{
   setCourseName( name );  
   aCount = 0; 
   bCount = 0;
   cCount = 0; 
   dCount = 0; 
   fCount = 0;
}

void GradeBook::setCourseName( string name )
{
   if ( name.length() <= 25 )
      courseName = name;
   else
   { 
      courseName = name.substr( 0, 25 ); 
      cout << "Name \"" << name << "\" exceeds maximum length (25).\n"
         << "Limiting courseName to first 25 characters.\n" << endl;
   } 
} 

string GradeBook::getCourseName()
{
   return courseName;
} 

void GradeBook::displayMessage()
{
   cout << "Welcome to the grade book for\n" << getCourseName() << "!\n" 
      << endl;
} 

void GradeBook::inputGrades()
{
   int grade; 
   cout << "Enter the letter grades." << endl
      << "Enter the EOF character to end input." << endl;
   while ( ( grade = cin.get() ) != EOF )
   {
      switch ( grade ) 
      {
         case 'A': 
         case 'a': 
            aCount++; 
            break; 
         case 'B':
         case 'b':
            bCount++; 
            break; 
         case 'C': 
         case 'c':
            cCount++; 
            break; 
         case 'D': 
         case 'd':
            dCount++; 
            break; 
         case 'F':
         case 'f': 
            fCount++; 
            break; 
         case '\n': 
         case '\t':
         case ' ': 
            break; 
         default: 
            cout << "Incorrect letter grade entered."
               << " Enter a new grade.\n";
            break;
      } 
   } 
} 

void GradeBook::displayGradeReport()
{
    cout << "\n\nNumber of students who received each letter grade:" 
      << "\nA: " << aCount << "\nB: " << bCount 
      << "\nC: " << cCount  
      << "\nD: " << dCount << "\nF: " << fCount << endl;
   int gradeCount = aCount + bCount + cCount + dCount + fCount;
   if ( gradeCount != 0 )
   {
      int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;
      cout << fixed << setprecision( 1 );
      cout << "\nThe class average is: " 
         << static_cast< double > ( gradeTotal ) / gradeCount
         << endl;
   } 
}
//main.cpp
#include "GradeBook.h"

int main()
{
   GradeBook myGradeBook( "CS101 C++ Programming" );
   myGradeBook.displayMessage(); 
   myGradeBook.inputGrades(); 
   myGradeBook.displayGradeReport(); 
}

5.16(复利计算)

#include <iostream> 
#include <iomanip>  // parameterized stream manipulators
#include <cmath>
using namespace std;

int main()
{
   int amount; 
   int principal = 100000; 
   int dollars;
   int cents; 
   double rate = .05; 
   cout << "Year" << setw( 24 ) << "Amount on deposit\n";
   for ( int year = 1; year <= 10; year++ )
   {
      amount = static_cast< int >( principal * pow( 1.0 + rate, year ) );
      cents = amount % 100;
      dollars = amount / 100;
      cout << setw( 4 ) << year << setw( 20 ) << dollars << '.';
      if ( cents < 10 )
         cout << '0' << cents << endl;
      else 
         cout << cents << endl;
   } 
}

5.18(进制表)

#include <iostream>
using namespace std; 

int main()
{
   int number; 
   int factor;
   cout << "Decimal\t\tBinary\t\tOctal\tHexadecimal\n";
   for ( int loop = 1; loop <= 256; loop++ ) 
   {
      cout << dec << loop << "\t\t";
      number = loop;
      factor = 256;
      cout << ( number == 256 ? '1' : '0' );
      do 
      {     
         cout << ( number < factor && number >= ( factor / 2 ) ? '1' : '0' );
         factor /= 2;
         number %= factor;
      } while ( factor > 1 
      cout << '\t' << oct << loop;
      cout << '\t' << hex << loop << endl;
   } 
}

5.19(求Π的值)

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

int main()
{
   long double pi = 0.0;
   long double denom = 1.0; 
   long accuracy = 1000;
   cout << fixed << setprecision( 8 );
   cout << "Accuracy set at: " << accuracy << "\n\nterm\t\tpi\n";
   for ( long loop = 1; loop <= accuracy; loop++ ) 
   {
      if ( loop % 2 != 0 ) 
         pi += 4.0 / denom;
      else
         pi -= 4.0 / denom;
      cout << loop << "\t\t" << pi << '\n';
      denom += 2.0; // update denominator
   } 
   cout << endl;
}

5.20(毕达哥拉斯的三元组)

#include <iostream>
using namespace std;

int main()
{
   int count = 0; 
   long int hypotenuseSquared;
   long int sidesSquared; /
   cout << "Side 1\tSide 2\tSide3" << endl;
   for ( long side1 = 1; side1 <= 500; side1++ ) 
   {
      for ( long side2 = side1; side2 <= 500; side2++ ) 
      {
         for ( long hypotenuse = side2; hypotenuse <= 500; hypotenuse++ ) 
         {
            hypotenuseSquared = hypotenuse * hypotenuse;
            sidesSquared = side1 * side1 + side2 * side2;
            if ( hypotenuseSquared == sidesSquared ) 
            {
               cout << side1 << '\t' << side2 << '\t' << hypotenuse << '\n';
               count++; 
            } 
         } 
      } 
   }
   cout << "A total of " << count << " triples were found." << endl;
} 

5.21(薪金计算)

#include <iostream>
#include <iomanip> // parameterized stream manipulators
using namespace std; 

int main()
{
   int payCode; 
   int pieces; 
   double salary; 
   double hours;
   double pay; 
   cout << "Enter paycode (-1 to end): ";
   cin >> payCode;   
   cout << fixed << setprecision( 2 );
   while ( payCode != -1 ) 
   {
      switch ( payCode ) 
      {
         case 1: 
            cout << "Manager selected.\nEnter weekly salary: ";
            cin >> salary;
            cout << "The manager's pay is $" << salary << '\n';
            break; 
         case 2: 
            cout << "Hourly worker selected.\n"
               << "Enter the hourly salary: ";
            cin >> salary;
            cout << "Enter the total hours worked: ";
            cin >> hours;
            pay = ( hours > 40.0 ? ( hours - 40 ) * 1.5 * salary
                + salary * 40.0 : salary * hours );
            cout << "Worker's pay is $" << pay << '\n';
            break; 
         case 3:
            cout << "Commission worker selected.\n"
                 << "Enter gross weekly sales: ";
            cin >> salary;
            pay = 250.0 + 0.057 * salary;
            cout << "Commission worker's pay is $" << pay << '\n';
            break; 
         case 4: /
            cout << "Pieceworker selected.\n" 
               << "Enter number of pieces: ";
            cin >> pieces;
            cout << "Enter wage per piece: ";
            cin >> salary;
            pay = pieces * salary; // compute pay 
            cout << "Pieceworker's pay is $" << pay << '\n';
            break; 
         default: // default case
            cout << "Invalid pay code.\n";
            break;
      } 
      cout << "\nEnter paycode (-1 to end): ";
      cin >> payCode;
   } // end while
}

5.22(德摩根定律)

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

int main()
{ 
   int x = 6; 
   int y; 
   cout << boolalpha << "PART A" << endl << endl;
   do 
   {   
      x--; 
      y = 5; 
      do 
      {
         y++; 
         cout << "!( x < 5 ): " << !( x < 5 ) << endl;
         cout << "!( y >= 7 ): " << !( y >= 7 ) << endl;  
         if ( ( !( x < 5 ) && !( y >= 7 ) ) == 
              ( !( ( x < 5 ) || ( y >= 7 ) ) ) )
            cout << "!(x < 5) && !(y >= 7) is equivalent to"
               << " !((x < 5) || (y >= 7))" << endl;
         else
            cout << "!(x < 5) && !(y >= 7) is not equivalent to"
               << " !((x < 5) || (y >= 7))" << endl;
         cout << endl;
      } while ( !( y >= 7 ) );
   } while ( !( x < 5 ) ); // end do...while
   cout << endl << endl;
   int a = 3;
   int b = 5; 
   int g;
   cout << "PART B" << endl << endl;
   do 
   {
      a++; 
      g = 4; 
      do 
      {
         g++; 
         cout << "!( a == b): " << !( a == b ) << endl;
         cout << "!( g != 5): " << !( g != 5 ) << endl;
         if ( ( !( a == b ) || !( g != 5 ) ) ==
              ( !( ( a == b ) && ( g != 5 ) ) ) ) 
            cout << "!(a == b) || !(g != 5) is equivalent to"
               << " !((a == b) && (g != 5))" << endl;
         else
            cout << "!(a == b) || !(g != 5) is not equivalent to"
               << " !((a == b) && (g != 5))" << endl;
         cout << endl;
      } while ( !( g != 5 ) ); 
   } while ( !( a == b ) ); 
   cout << endl << endl;
   x = 7;   
   cout << "PART C" << endl << endl;
   do 
   {
      x++; 
      y = 6; 
      do
      {
         y--; 
         cout << "( x <= 8 ): " << ( x <= 8 ) << endl;
         cout << "( y > 4 ): " << ( y > 4 ) << endl;
         if ( !( ( x <= 8 ) && ( y > 4 ) ) == 
              ( !( x <= 8 ) || !( y > 4 ) ) )
            cout << "!((x <= 8) && (y > 4)) is equivalent to"
               << " !(x <= 8) || !(y > 4)" << endl;
         else
            cout << "!((x <= 8) && (y > 4)) is not equivalent to"
               << " !(x <= 8) || !(y > 4)" << endl;

         cout << endl;
      } while ( ( y > 4 ) ); 
   } while ( ( x <= 8 ) ); 
   cout << endl << endl;
   int i = 6;
   int j; 
   cout << "PART D" << endl << endl;
   do 
   {   
      i--; 
      j = 5;
      do 
      {
         j++; 
         cout << "( i > 4 ): " << ( i > 4 ) << endl;
         cout << "( j <= 6 ): " << ( j <= 6 ) << endl;
         if ( !( ( i > 4 ) || ( j <= 6 ) ) == 
            ( !( i > 4 ) && !( j <= 6 ) ) )
            cout << "!((i > 4) || (j <= 6)) is equivalent to"
               << " !(i > 4) && !(j <= 6)" << endl;
         else
            cout << "!((i > 4) || (j <= 6)) is not equivalent to"
               << " !(i > 4) && !(j <= 6)" << endl;
         cout << endl;
      } while ( ( j <= 6 ) );
   } while ( ( i > 4 ) ); 

5.23(星号组成的菱形图案)

#include <iostream>
using namespace std; 

int main()
{
   for ( int row = 1; row <= 5; row++ ) 
   {
      for ( int space = 1; space <= 5 - row; space++ )
         cout << ' ';
      for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ ) 
         cout << '*';
      cout << '\n';
   } 
   for ( int row = 4; row >= 1; row-- ) 
   {
      for ( int space = 1; space <= 5 - row; space++ )
         cout << ' ';
      for ( int asterisk = 1; asterisk <= 2 * row - 1; asterisk++ ) 
         cout << '*';
         cout << '\n';
   } 
   cout << endl;
}

5.24(修改星号组成的菱形图案)

#include <iostream>
using namespace std; 

int main()
{
   int size;
   do 
   {    
      cout << "Enter an odd number for the diamond size (1-19): \n";
      cin >> size;
   } while ( ( size < 1 ) || ( size > 19 ) || ( ( size % 2 ) != 1 ) );
   for ( int rows = 1; rows <= size - 2; rows += 2 ) 
   {
      for ( int space = ( size - rows ) / 2; space > 0; space-- )
         cout << ' ';
      for ( int asterisk = 1; asterisk <= rows; asterisk++ )
         cout << '*';
      cout << '\n';
   }
   for ( int rows = size; rows >= 0; rows -= 2 ) 
   {
      for ( int space = ( size - rows ) / 2; space > 0; space-- )
         cout << ' ';
      for ( int asterisk = 1; asterisk <= rows; asterisk++ )
         cout << '*';
      cout << '\n';
   } 
   cout << endl;
}

5.25(去除break和continue)

#include <iostream> 
using namespace std;

int main()
{
   int count; 
   bool breakOut = false;
   for ( count = 1; ( count <= 10 ) && ( !breakOut ); count++ )
   {
      if ( count == 5 ) 
         breakOut = true; /
      else
         cout << count << " ";
   } 
   cout << "\nBroke out of loop because loop-continuation test "
      << "( !breakOut ) failed." << endl;
} 

5.27

#include <iostream>
using namespace std;

int main()
{
   for ( int count = 1; count <= 10; count++ ) 
   {
      if ( count != 5 ) 
         cout << count << " ";
   }
   cout << "\nUsed if condition to skip printing 5" << endl;
}

5.28(歌曲“圣诞节的十二天”)

#include <iostream>
using namespace std; 

int main()
{
   for ( int day = 1; day <= 12; day++ ) 
   {
      cout << "On the ";
      switch ( day ) 
      {       
         case 1:
            cout << "first";
            break;
         case 2:
            cout << "second";
            break;
         case 3:
            cout << "third";
            break;
         case 4:
            cout << "fourth";
            break;
         case 5:
            cout << "fifth";
            break;
         case 6:
            cout << "sixth";
            break;
         case 7:
            cout << "seventh";
            break;
         case 8:
            cout << "eighth";
            break;
         case 9:
            cout << "ninth";
            break;
         case 10:
            cout << "tenth";
            break;
         case 11:
            cout << "eleventh";
            break;
         case 12:
            cout << "twelfth";
            break;
      } 
      cout << " day of Christmas,\nMy true love sent to me:\n";
      switch ( day ) 
      {   
         case 12:
            cout << "\tTwelve drummers drumming,\n";
         case 11:
            cout << "\tEleven pipers piping,\n";
         case 10:
            cout << "\tTen lords a-leaping,\n";
         case 9:
            cout << "\tNine ladies dancing,\n";
         case 8:
            cout << "\tEight maids a-milking,\n";
         case 7:
            cout << "\tSeven swans a-swimming,\n";
         case 6:
            cout << "\tSix geese a-laying,\n";
         case 5:
            cout << "\tFive golden rings,\n";
         case 4:
            cout << "\tFour calling birds,\n";
         case 3:
            cout << "\tThree French hens,\n";
         case 2:
            cout << "\tTwo turtle doves, and\n";
         case 1:
            cout << "A partridge in a pear tree.\n\n\n";
      } 
   } 
   cout << endl;
}