⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 selsolutions5.txt

📁 一本很好的C++学习的丛书!初学者必看的
💻 TXT
📖 第 1 页 / 共 5 页
字号:
    char filename[SIZE];
    char ch;
    ifstream inFile;        // object for handling file input

    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE);
    inFile.open(filename);  // associate inFile with a file
    if (!inFile.is_open())  // failed to open file
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        exit(EXIT_FAILURE);
    }
    int count = 0;          // number of items read

    inFile >> ch;        // get first value
    while (inFile.good())   // while input good and not at EOF
    {
        count++;            // one more item read
        inFile >> ch;    // get next value
    }

    cout << count << " characters in " << filename << endl;

    inFile.close();         // finished with the file
    return 0;
}

Chapter 7


//pe7-1.cpp -- harmonic mean

#include <iostream>

double h_mean(double x, double y);

int main(void)
{
    using namespace std;
    double x,y;

    cout << "Enter two numbers (a 0 terminates): ";
    while (cin >> x >> y && x * y != 0)
        cout << "harmonic mean of " << x << " and "
             << y << " = " << h_mean(x,y) << "\n";
/* or do the reading and testing in two parts:
    while (cin >> x && x != 0)
    {
        cin >> y;
        if (y == 0)
            break;
            ...
*/
    cout << "Bye\n";
    return 0;
}

double h_mean(double x, double y)
{
    return 2.0 * x * y / (x + y);
}


// pe7-3.cpp

#include <iostream>

struct box {
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};

void showbox(box b);
void setbox(box * pb);

int main(void)
{
    box carton = {"Bingo Boxer", 2, 3, 5}; // no volume provided
    setbox(&carton);
    showbox(carton);
    return 0;
}

void showbox(box b)
{
    using namespace std;
    cout << "Box maker: " << b.maker
         << "\nheight: " << b.height
         << "\nlwidth: " << b.width
         << "\nlength: " << b.length
         << "\nvolume: " << b.volume << "\n";
}

void setbox(box * pb)
{
    pb->volume = pb->height * pb->width * pb->length;
}


// pe7-4.cpp -- probability of winning
#include <iostream>
long double probability(unsigned numbers, unsigned picks);

int main()
{
    using namespace std;
    double total, choices;
    double mtotal;
    double probability1, probability2;
    cout << "Enter total number of game card choices and\n"
            "number of picks allowed for the field:\n";
    while ((cin >> total >> choices) && choices <= total)
    {
        cout << "Enter total number of game card choices "
                "for the mega number:\n";
        if (!(cin >> mtotal))
            break;
        cout << "The chances of getting all " << choices << " picks is one in "
             << (probability1 = probability(total, choices) ) << ".\n";
        cout << "The chances of getting the megaspot is one in "
             << (probability2 = probability(mtotal, 1) ) << ".\n";
        cout << "You have one chance in ";
        cout << probability1 * probability2;      // compute the probability
        cout << " of winning.\n";
        cout << "Next set of numbers (q to quit): ";
    }
    cout << "bye\n";
    return 0;
}

// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
    long double result = 1.0;  // here come some local variables
    long double n;
    unsigned p;

    for (n = numbers, p = picks; p > 0; n--, p--)
        result = result * n / p ; 
    return result;
}
// pe7-6.cpp
#include <iostream>
int Fill_array(double ar[], int size);
void Show_array(const double ar[], int size);
void Reverse_array(double ar[], int size);
const int LIMIT = 10;

int main( )
{
    using namespace std;
    double values[LIMIT];
    
    int entries = Fill_array(values, LIMIT);
    cout << "Array values:\n";
    Show_array(values, entries);
    cout << "Array reversed:\n";
    Reverse_array(values, entries);
    Show_array(values, entries);    
    cout << "All but end values reversed:\n";
    Reverse_array(values + 1, entries - 2);
    Show_array(values, entries);

    return 0;
}

int Fill_array(double ar[], int size)
{
    using namespace std;
    int n;
    cout << "Enter up to " << size << " values (q to quit):\n";
    for (n = 0; n < size; n++)
    {
        cin >> ar[n];
        if (!cin)
            break;
    }
    return n;
}

void Show_array(const double ar[], int size)
{
    using namespace std;
    int n;
    for (n = 0; n < size; n++)
    {
        cout << ar[n];
        if (n % 8 == 7)
            cout << endl;
        else
            cout << ' ';
    }
    if (n % 8 != 0)
        cout << endl;
}
void Reverse_array(double ar[], int size)
{
    int i, j;
    double temp;
    
    for (i = 0, j = size - 1; i < j; i++, j--)
    {
        temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
}

//pe7-9.cpp

#include <iostream>

double calculate(double x, double y, double (*pf)(double, double));
double add(double x, double y);
double sub(double x, double y);
double mean(double x, double y);

int main(void)
{
    using namespace std;
    double (*pf[3])(double,double) = {add, sub, mean};
    char * op[3] = {"sum", "difference", "mean"};
    double a, b;
    cout << "Enter pairs of numbers (q to quit): ";
    int i;
    while (cin >> a >> b)
    {
        // using function names
        cout << calculate(a, b, add) << " = sum\n";
        cout << calculate(a, b, mean) << " = mean\n";
        // using pointers
        for (i = 0; i < 3; i++)
            cout << calculate(a, b, pf[i]) << " = "
                 << op[i] << "\n";
    }
    cout << "Done!\n";
    return 0;
}

double calculate(double x, double y, double (*pf)(double, double))
{
    return (*pf)(x, y);
}

double add(double x, double y)
{
    return x + y;
}

double sub(double x, double y)
{
    return x - y;
}

double mean(double x, double y)
{
    return (x + y) / 2.0;
}


Chapter 8

// pe8-1.cpp
#include <iostream>
void silly(const char * s, int n = 0);
int main(void)
{
    using namespace std;
    char * p1 = "Why me?\n";

    silly(p1);
    for (int i = 0; i < 3; i++)
    {
        cout << i << " = i\n";
        silly(p1, i);
    }
    cout << "Done\n";
    return 0;
}

void silly(const char * s, int n)
{
    using namespace std;
    static int uses = 0;

    int lim = ++uses;
    if (n == 0)
        lim = 1;
    for (int i = 0; i < lim; i++)
        cout << s;
}


// pe8-4.cpp
#include <iostream>
#include <cstring>    // for strlen(), strcpy()
using namespace std;

struct stringy {
    char * str;        // points to a string
    int ct;        // length of string (not counting '\0')
    };


void show(const char *str, int cnt =  1);
void show(const stringy & bny, int cnt = 1);
void set(stringy & bny, const char * str);

int main(void)
{
    stringy beany;
    char testing[] = "Reality isn't what it used to be.";

    set(beany, testing);    // first argument is a reference,
            // allocates space to hold copy of testing,
            // sets str member of beany to point to the
            // new block, copies testing to new block,
            // and sets ct member of beany
    show(beany);        // prints member string once
    show(beany, 2);    // prints member string twice
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);    // prints testing string once
    show(testing, 3);    // prints testing string thrice
    show("Done!");
    return 0;
}

void show(const char *str, int cnt)
{
    while(cnt-- > 0)
    {
            cout << str << endl;
    }
}

void show(const stringy & bny, int cnt)
{
    while(cnt-- > 0)
    {
            cout << bny.str << endl;
    }
}

void set(stringy & bny, const char * str)
{
    bny.ct = strlen(str);
    bny.str = new char[bny.ct+1];
    strcpy(bny.str, str);
}


// pe8-5.cpp
#include <iostream>

template <class T>
T max5(T ar[])
{
    int n;
    T max = ar[0];
    for (n = 1; n < 5; n++)
        if (ar[n] > max)
            max = ar[n];
    return max;
}

const int LIMIT = 5;
int main( )
{
    using namespace std;
    double ard[LIMIT] = { -3.4, 8.1, -76.4, 34.4, 2.4};
    int ari[LIMIT] = {2, 3, 8, 1, 9};
    double md;
    int mi;
    
    md = max5(ard);
    mi = max5(ari);
    
    cout << "md = " << md << endl;
    cout << "mi = " << mi << endl;
    
    return 0;
}

Chapter 9
PE 9-1


// pe9-golf.h - for pe9-1.cpp
const int Len = 40;
struct golf
{
    char fullname[Len];
    int handicap;
};

// non-interactive version
// function sets golf structure to provided name, handicap
// using values passed as arguments to the function
void setgolf(golf & g, const char * name, int hc);

// interactive version
// function solicits name and handicap from user
// and sets the members of g to the values entered
// returns 1 if name is entered, 0 if name is empty string
int setgolf(golf & g);

// function resets handicap to new value
void handicap(golf & g, int hc);

// function displays contents of golf structure
void showgolf(const golf & g);


// pe9-golf.cpp - for pe9-1.cpp
#include <iostream>
#include "pe9-golf.h"
#include <cstring>

// function solicits name and handicap from user
// returns 1 if name is entered, 0 if name is empty string
int setgolf(golf & g)
{
    std::cout << "Please enter golfer's full name: ";
    std::cin.getline(g.fullname, Len);
    if (g.fullname[0] == '\0')
        return 0;                // premature termination
    std::cout << "Please enter handicap for " << g.fullname << ": ";
    while (!(std::cin >> g.handicap))
    {
        std::cin.clear();
        std::cout << "Please enter an integer: ";
    }
    while (std::cin.get() != '\n')
        continue;
    return 1;
}

// function sets golf structure to provided name, handicap
void setgolf(golf & g, const char * name, int hc)
{
    std::strcpy(g.fullname, name);
    g.handicap = hc;
}

// function resets handicap to new value
void handicap(golf & g, int hc)
{
    g.handicap = hc;
}

// function displays contents of golf structure
void showgolf(const golf & g)
{
    std::cout << "Golfer:   " << g.fullname << "\n";
    std::cout << "Handicap: " << g.handicap << "\n\n";
}


// pe9-1.cpp
#include <iostream>
#include "pe9-golf.h"
// link with pe9-golf.cpp
const int Mems = 5;
int main(void)
{
    using namespace std;
    golf team[Mems];

    cout << "Enter up to " << Mems << " golf team members:\n";
    int i;
    for (i = 0; i < Mems; i++)
        if (setgolf(team[i]) == 0)
            break;
    for (int j = 0; j < i; j++)
        showgolf(team[j]);
    setgolf(team[0], "Fred Norman", 5);
    showgolf(team[0]);
    handicap(team[0], 3);
    showgolf(team[0]);

    return 0;
}


PE 9-3

//pe9-3.cpp -- using placement new
#include <iostream>
#include <new>
#include <cstring>
struct chaff
{
    char dross[20];
    int slag;
};

// char buffer[500]; // option 1
int main()
{
    using std::cout;
    using std::endl;
    chaff *p1;
    int i;
    char * buffer = new char [500];  // option 2
    p1 = new (buffer) chaff[2];    // place structures in buffer
    std::strcpy(p1[0].dross, "Horse Feathers");
    p1[0].slag = 13;
    std::strcpy(p1[1].dross, "Piffle");
    p1[1].slag = -39;

    for (i = 0; i < 2; i++)
        cout << p1[i].dross << ": " << p1[i].slag << endl;
    delete [] buffer;  // option 2

    return 0;
}
Chapter 10

PE 10-1

// pe10-1.cpp
#include <iostream>
#include <cstring>

// class declaration
class BankAccount 
{
private:
    char name[40];
    char acctnum[25];
    double balance;
public:
    BankAccount(char * client = "no one", char * num = "0",
                 double bal = 0.0);     void show(void) const;
    void deposit(double cash);     void withdraw(double cash);
};

// method definitions
BankAccount::BankAccount(char * client, char * num, double bal)
{
    std::strncpy(name, client, 39);
    name[39] = '\0';
    std::strncpy(acctnum, num, 24);
    acctnum[24] = '\0';
    balance = bal;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -