Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lafore_robert_objectoriented_programming_in_c

.pdf
Скачиваний:
51
Добавлен:
27.03.2023
Размер:
8.94 Mб
Скачать

Answers to Questions and Exercises

925

22.faster, more

23.inline float foobar(float fvar)

24.a, b

25.char blyth(int, float=3.14159);

26.visibility, lifetime

27.those functions defined following the variable definition

28.the function in which it is defined

29.b, d

30.on the left side of the equal sign

Solutions to Exercises

1.

//ex5_1.cpp

//function finds area of circle #include <iostream>

using namespace std;

float circarea(float radius);

int main()

{

double rad;

cout << “\nEnter radius of circle: “; cin >> rad;

cout << “Area is “ << circarea(rad) << endl; return 0;

}

//--------------------------------------------------------------

float circarea(float r)

{

const float PI = 3.14159F; return r * r * PI;

}

2.

//ex5_2.cpp

//function raises number to a power #include <iostream>

using namespace std;

double power( double n, int p=2); //p has default value 2

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

926

int main()

{

 

 

double number, answer;

 

int pow;

 

char

yeserno;

 

cout

<< “\nEnter number: “;

//get number

cin >> number;

 

cout

<< “Want to enter a power (y/n)? “;

cin >> yeserno;

 

if( yeserno == ‘y’ )

//user wants a non-2 power?

{

 

 

cout << “Enter power: “;

 

cin >> pow;

 

answer = power(number, pow);

//raise number to pow

}

 

 

else

 

 

answer = power(number);

//square the number

cout

<< “Answer is “ << answer << endl;

return 0;

}

//--------------------------------------------------------------

//power()

//returns number n raised to a power p double power( double n, int p )

{

double result = 1.0;

//start with 1

for(int j=0;

j<p; j++)

//multiply by n

result *=

n;

//p times

return result;

}

3.

//ex5_3.cpp

//function sets smaller of two numbers to 0 #include <iostream>

using namespace std;

int main()

{

void zeroSmaller(int&, int&); int a=4, b=7, c=11, d=9;

zeroSmaller(a, b); zeroSmaller(c, d);

Answers to Questions and Exercises

927

cout << “\na=” << a << “ b=” << b << “ c=” << c << “ d=” << d;

return 0;

}

//--------------------------------------------------------------

//zeroSmaller()

//sets the smaller of two numbers to 0 void zeroSmaller(int& first, int& second)

{

if( first < second ) first = 0;

else

second = 0;

}

4.

//ex5_4.cpp

//function returns larger of two distances #include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

struct Distance

// English distance

{

 

int feet;

 

float inches;

 

};

 

////////////////////////////////////////////////////////////////

Distance bigengl(Distance, Distance); //declarations void engldisp(Distance);

int main()

 

 

 

{

 

 

 

 

Distance d1, d2,

d3;

//define three lengths

 

 

 

//get length d1 from user

cout

<< “\nEnter

feet: “;

cin >>

d1.feet;

cout

<< “Enter inches: “;

cin >>

d1.inches;

 

 

 

//get length d2 from user

cout

<< “\nEnter

feet: “;

cin >>

d2.feet;

cout

<< “Enter inches: “;

cin >>

d2.inches;

d3 =

bigengl(d1,

d2);

//d3

is larger of d1 and d2

 

 

 

//display all lengths

cout

<< “\nd1=”;

engldisp(d1);

 

cout

<< “\nd2=”;

engldisp(d2);

 

cout

<< “\nlargest is “; engldisp(d3); cout << endl;

return 0;

}

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

928

//--------------------------------------------------------------

//bigengl()

//compares two structures of type Distance, returns the larger Distance bigengl( Distance dd1, Distance dd2 )

{

if(dd1.feet > dd2.feet)

//if feet are different, return

return dd1;

//the one with the largest feet

if(dd1.feet < dd2.feet)

 

return dd2;

 

if(dd1.inches > dd2.inches)

//if inches are different,

return dd1;

//return one with largest

else

//inches, or dd2 if equal

return dd2;

 

}

 

//--------------------------------------------------------------

 

//engldisp()

//display structure of type Distance in feet and inches void engldisp( Distance dd )

{

cout << dd.feet << “\’-” << dd.inches << “\””;

}

Chapter 6

Answers to Questions

1.A class declaration describes how objects of a class will look when they are created.

2.class, object

3.c

4.

class leverage

{

private:

int crowbar; public:

void pry();

};

5.false; both data and functions can be private or public

6.leverage lever1;

7.d

8.lever1.pry();

9.inline (also private)

Answers to Questions and Exercises

10.

int getcrow()

{return crowbar; }

11.created (defined)

12.the class of which it is a member

leverage()

{crowbar = 0; }

14.true

15.a

16.int getcrow();

17.

int leverage::getcrow()

{ return crowbar; }

18.member functions and data are, by default, public in structures but private in classes

19.three, one

20.calling one of its member functions

21.b, c, d

22.false; trial and error may be necessary

23.d

24.true

25.void aFunc(const float jerry) const;

Solutions to Exercises

1.

//ex6_1.cpp

//uses a class to model an integer data type #include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

class Int

//(not the same as int)

{

 

private:

 

int i;

 

public:

 

Int()

//create an Int

{ i = 0; }

 

929

G

Q E UESTIONS ANSWERS XERCISES AND TO

930

Appendix G

 

Int(int ii)

 

//create and initialize an Int

{ i = ii;

}

 

void

add(Int

i2, Int i3) //add two Ints

{

i = i2.i + i3.i; }

 

void

display()

//display an Int

{

cout <<

i; }

 

};

////////////////////////////////////////////////////////////////

int main()

 

 

{

 

 

Int Int1(7);

//create

and initialize an Int

Int Int2(11);

//create

and initialize an Int

Int Int3;

//create

an Int

Int3.add(Int1, Int2);

 

//add two Ints

cout << “\nInt3 = “; Int3.display();

//display result

cout << endl;

 

 

return 0;

 

 

}

 

 

2.

//ex6_2.cpp

//uses class to model toll booth #include <iostream>

using namespace std; #include <conio.h>

const

char ESC = 27;

//escape key

ASCII code

const

double TOLL = 0.5;

//toll is 50

cents

////////////////////////////////////////////////////////////////

class tollBooth

 

{

 

private:

 

unsigned int totalCars;

//total cars passed today

double totalCash;

//total money collected today

public:

//constructor

tollBooth() : totalCars(0), totalCash(0.0)

{}

void

payingCar()

//a

car

paid

{

totalCars++; totalCash += TOLL; }

 

 

 

void

nopayCar()

//a

car

didn’t pay

{

totalCars++; }

 

 

 

void

display() const

//display totals

{cout << “\nCars=” << totalCars

<<“, cash=” << totalCash

<<endl; }

};

Answers to Questions and Exercises

931

////////////////////////////////////////////////////////////////

int main()

{

tollBooth booth1; //create a toll booth char ch;

cout << “\nPress

0

for each

non-paying car,”

<< “\n

1

for each

paying car,”

<< “\n

Esc to exit the program.\n”;

do {

 

 

 

ch = getche();

 

 

//get character

if( ch == ‘0’

)

 

//if it’s 0, car didn’t pay

booth1.nopayCar();

 

if( ch == ‘1’

)

 

//if it’s 1, car paid

booth1.payingCar();

 

} while( ch != ESC );

//exit loop on Esc key

booth1.display();

 

 

//display totals

return 0;

 

 

 

}

 

 

 

3.

//ex6_3.cpp

//uses class to model a time data type #include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

class time

{

private:

int hrs, mins, secs; public:

time() : hrs(0), mins(0), secs(0) //no-arg constructor

{}

//3-arg constructor time(int h, int m, int s) : hrs(h), mins(m), secs(s)

{}

void

display() const

//format 11:59:59

{

cout << hrs << “:” << mins << “:” << secs; }

void

add_time(time t1, time t2)

//add two times

{

 

 

secs

= t1.secs + t2.secs;

//add seconds

if( secs > 59 )

//if overflow,

{

secs -= 60; mins++; }

//

carry a minute

mins

+= t1.mins + t2.mins;

//add minutes

G

Q E UESTIONS ANSWERS XERCISES AND TO

932

Appendix G

 

if( mins > 59 )

//if

overflow,

{ mins -= 60; hrs++; }

//

carry an hour

hrs += t1.hrs + t2.hrs;

//add hours

}

 

 

};

////////////////////////////////////////////////////////////////

int main()

 

{

 

const time time1(5, 59, 59);

//creates and initialze

const time time2(4, 30, 30);

// two times

time time3;

//create another time

time3.add_time(time1, time2);

//add two times

cout << “time3 = “; time3.display();

//display result

cout << endl;

 

return 0;

 

}

 

Chapter 7

Answers to Questions

1.d

2.same

3.double doubleArray[100];

4.0, 9

5.cout << doubleArray[j];

6.c

7.int coins[] = { 1, 5, 10, 25, 50, 100 };

8.d

9.twoD[2][4]

10.true

11.float flarr[3][3] = { {52,27,83}, {94,73,49}, {3,6,1} };

12.memory address

13.a, d

14.an array with 1000 elements of structure or class employee

15.emplist[16].salary

16.d

Answers to Questions and Exercises

933

17.bird manybirds[50];

18.false

19.manybirds[26].cheep();

20.array, char

21.char city[21] (An extra byte is needed for the null character.)

22.char dextrose[] = “C6H12O6-H2O”;

23.true

24.d

25.strcpy(blank, name);

26.

class dog

{

private:

char breed[80]; int age;

};

27.false

28.b, c

29.int n = s1.find(“cat”);

30.s1.insert(12, “cat”);

Solutions to Exercises

1.

// ex7_1.cpp

 

// reverses a C-string

 

#include <iostream>

 

#include <cstring>

//for strlen()

using namespace std;

 

int main()

 

{

 

void reversit( char[] );

//prototype

const int MAX = 80;

//array size

char str[MAX];

//string

cout << “\nEnter a string: “;

//get string from user

cin.get(str, MAX);

 

G

Q E UESTIONS ANSWERS XERCISES AND TO

934

Appendix G

 

reversit(str);

//reverse the string

cout <<

“Reversed string is: “;

//display it

cout <<

str << endl;

 

 

return 0;

 

 

}

 

 

 

//--------------------------------------------------------------

 

 

 

//reversit()

 

 

//function

to reverse a string passed to it as an argument

void reversit( char s[] )

 

 

{

 

 

 

int len

= strlen(s);

//find length of string

for(int

j = 0; j < len/2; j++)

//swap each character

{

 

//

in first half

char

temp = s[j];

//

with character

s[j]

= s[len-j-1];

//

in second half

s[len-j-1] = temp;

}

}

//reversit()

//function to reverse a string passed to it as an argument void reversit( char s[] )

{

int len

= strlen(s);

// find

length of string

for(int

j

= 0;

j < len/2; j++)

// swap

each character

{

 

 

 

//

in

first half

char

temp =

s[j];

//

with character

s[j]

=

s[len-j-1];

//

in

second half

s[len-j-1] = temp;

}

}

2.

//ex7_2.cpp

//employee object uses a string as data #include <iostream>

#include <string> using namespace std;

////////////////////////////////////////////////////////////////

class employee

{

private:

string name; long number;