1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ Primer Plus (P72) potx

20 512 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 41,99 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Most important, the first statement assigns the letter A to grade only on a system using the ASCII code, while the second statement also works for other codes.. Second, 65 is a type int

Trang 1

cout << "We have " << cheeses << " varieties of cheese\n";

.9: What does the following function header tell you about the function?

A: It tells us that the function froop() expects to be called with one argument, which will be type double, and that the function will return a type int

value

.10: When do you not have to use the keyword return when you define a

function?

A: You don't have to use return in a function when the function has return type void However, you can use it providing you don't give a return value:

return;

Chapter 3

.1: Why does C++ have more than one integer type?

A: Having more than one integer type lets you choose the type best suited to a particular need For example, you could use short to conserve space, long to guarantee storage capacity, or find that a particular type speeds up a particular calculation

.2: Define the following:

A short integer with the value 80

a.

An unsigned int integer with the value 42110

b.

An integer with the value 3000000000

c.

Trang 2

short rbis = 80; // or short int rbis = 80;

unsigned int q = 42110; // or unsigned q = 42110;

unsigned long ants = 3000000000;

Note

Don't count on int being large enough to hold 3000000000

.3: What safeguards does C++ provide to keep you from exceeding the limits of an integer type?

A: C++ provides no automatic safeguards to keep you from exceeding integer limits; you can use the climits header file to determine what the limits are

.4: What is the distinction between 33L and 33?

A: The constant 33L is type long, whereas the constant 33 is type int

.5: Consider the two C++ statements that follow Are they equivalent?

char grade = 65;

char grade = 'A';

A: The two statements are not really equivalent, although they have the same effect on some systems Most important, the first statement assigns the letter A

to grade only on a system using the ASCII code, while the second statement also works for other codes Second, 65 is a type int constant, while 'A' is a type

char constant

.6: How could you use C++ to find out which character the code 88 represents?

Come up with at least two ways

A: Here are four ways:

Trang 3

char c = 88;

cout << c << "\n"; // char type prints as character cout.put(char(88)); // put() prints char as character cout << char(88) << "\n"; // new-style type cast value to char cout << (char)88 << "\n"; // old-style type cast value to char

.7: Assigning a long value to a float can result in a round-off error What about assigning long to double?

A: The answer depends on how large the two types are If long is 4 bytes, there is

no loss That's because the largest long value would be about 2 billion, which is

10 digits Because double provides at least 13 significant figures, no rounding would be needed

.8: Evaluate the following expressions as C++ would:

8 * 9 + 2

a.

6 * 3 / 4

b.

3 / 4 * 6

c.

6.0 * 3 / 4

d.

15 % 4

e.

A:

8 * 9 + 2 is 72 + 2 is 74

a.

6 * 3 / 4 is 18 / 4 is 4

b.

3 / 4 * 6 is 0 * 6 is 0

c.

6.0 * 3 / 4 is 18.0 / 4 is 4.5

d.

15 % 4 is 3

e.

Trang 4

.9: Suppose x1 and x2 are two type double variables that you want to add as integers and assign to an integer variable Construct a C++ statement for doing so

A: Either of the following work:

int pos = (int) x1 + (int) x2;

int pos = int(x1) + int(x2);

Chapter 4

.1: How would you declare each of the following?

actors is an array of 30 char

a.

betsie is an array of 100 short

b.

chuck is an array of 13 float

c.

dipsea is an array of 64 long double

d.

A:

char actors[30];

a.

short betsie[100];

b.

float chuck[13];

c.

long double dipsea[64];

d.

.2: Declare an array of five ints and initialize it to the first five odd positive integers

A:

int oddly[5] = {1, 3, 5, 7, 9};

Trang 5

.3: Write a statement that assigns the sum of the first and last elements of the array in question 2 to the variable even

A:

int even = oddly[0] + oddly[4];

.4: Write a statement that displays the value of the second element in the float array ideas

A:

cout << ideas[1] << "\n"; // or << endl;

.5: Declare an array of char and initialize it to the string "cheeseburger"

A:

char lunch[13] = "cheeseburger"; // number of characters + 1 or

char lunch[] = "cheeseburger"; // let the compiler count elements

.6: Devise a structure declaration that describes a fish The structure should include the kind, the weight in whole ounces, and the length in fractional inches

A:

struct fish { char kind[20];

int weight;

float length;

};

.7: Declare a variable of the type defined in question 6 and initialize it

Trang 6

fish petes = {

"trout", 13, 12.25 };

.8: Use enum to define a type called Response with the possible values of Yes,

No, and Maybe Yes should be 1, No should be 0, and Maybe should be 2

A:

enum Response {No, Yes, Maybe};

.9: Suppose ted is a double variable Declare a pointer that points to ted and use the pointer to display ted's value

A:

double * pd = &ted;

cout << *pd << "\n";

.10: Suppose treacle is an array of 10 floats Declare a pointer that points to the

first element of treacle and use the pointer to display the first and last elements of the array

A:

float * pf = treacle; // or = &treacle[0]

cout << pf[0] << " " << pf[9] << "\n";

// or use *pf and *(pf + 9)

.11: Write a code fragment that asks the user to enter a positive integer and then

creates a dynamic array of that many ints

Trang 7

unsigned int size;

cout << "Enter a positive integer: ";

cin >> size;

int * dyn = new int [size];

.12: Is the following valid code? If so, what does it print?

A: Yes, it is valid The expression "Home of the jolly bytes" is a string constant, hence it evaluates as the address of the beginning of the string The cout

object interprets the address of a char as an invitation to print a string, but the type cast (int *) converts the address to type pointer-to-int, which is then printed as an address In short, the statement prints the address of the string

.13: Write a code fragment that dynamically allocates a structure of the type

described in question 6 and then reads a value for the kind member of the structure

A:

struct fish {

char kind[20];

int weight;

float length;

};

fish * pole = new fish;

cout << "Enter kind of fish: ";

cin >> pole->kind;

Trang 8

.14: Listing 4.6 illustrates a problem with the following numeric input with

line-oriented string input How would replacing

cin.getline(address,80);

with

cin >> address;

affect the working of this program?

A: Using cin >> address causes a program to skip over whitespace until it finds nonwhitespace It then reads characters until it encounters whitespace again

Thus, it will skip over the newline following the numeric input, avoiding that problem On the other hand, it will read just a single word, not an entire line

Chapter 5

.1: What's the difference between an entry-condition loop and an exit-condition loop? Which kind is each of the C++ loops?

A: An entry-condition loop evaluates a test expression before entering the body of the loop If the condition initially is false, the loop never executes its body An exit-condition loop evaluates a test expression after processing the body of the loop Thus, the loop body is executed once even if the test expression initially is false The for and while loops are entry-condition loops, and the do while loop is an exit-condition loop

.2: What would the following code fragment print if it were part of a valid program?

int i;

for (i = 0; i < 5; i++) cout << i;

cout << "\n";

Trang 9

A: It would print the following:

01234 Note that the cout << "\n"; is not part of the loop body (no braces)

.3: What would the following code fragment print if it were part of a valid program?

int j;

for (j = 0; j < 11; j += 3) cout << j;

cout << "\n" << j << "\n";

A: It would print the following:

0369 12

.4: What would the following code fragment print if it were part of a valid program?

int j = 5;

while ( ++j < 9) cout << j++ << "\n";

A: It would print the following:

6 8

.5: What would the following code fragment print if it were part of a valid program?

int k = 8;

do cout <<" k = " << k << "\n";

while (k++ < 5);

Trang 10

A: It would print the following:

k = 8

.6: Write a for loop that prints the values 1 2 4 8 16 32 64 by increasing the value of a counting variable by a factor of 2 each cycle

A: It's simplest to use the *= operator:

for (int num = 1; num <= 64; num *= 2) cout << num << " ";

.7: How do you make a loop body include more than one statement?

A: You enclose the statements within paired braces to form a single compound statement, or block

.8: Is the following statement valid? If not, why not? If so, what does it do?

int x = (1,024);

What about the following?

int y;

y = 1,024;

A: Yes, the first statement is valid The expression 1,024 consists of two expressions?1 and 024?joined by a comma operator The value is the value of the right-hand expression This is 024, which is octal for 20, so the declaration assigns the value 20 to x The second statement also is valid

However, operator precedence causes it to be evaluated as follows:

(y = 1), 024;

That is, the left expression sets y to 1, and the value of the entire expression, which isn't used, is 024, or 20

.9: How does cin>>ch differ from cin.get(ch) and ch=cin.get() in how it

Trang 11

views input?

A: The cin >> ch form skips over spaces, newlines, and tabs when it encounters them The other two forms read these characters

Chapter 6

.1: Consider the following two code fragments for counting spaces and newlines:

// Version 1 while (cin.get(ch)) // quit on eof {

if (ch == ' ') spaces++;

if (ch == '\n') newlines++;

} // Version 2 while (cin.get(ch)) // quit on eof {

if (ch == ' ') spaces++;

else if (ch == '\n') newlines++;

} What advantages, if any, does the second form have over the first?

A: Both versions give the same answers, but the if else version is more efficient

Consider what happens, for example, when ch is a space Version 1, after incrementing spaces, tests to see whether the character is a newline This wastes time because the program already has established that ch is a space and hence could not be a newline Version 2, in the same situation, skips the newline test

Trang 12

.2: In Listing 6.2, what is the effect of replacing ++ch with ch+1?

A: Both ++ch and ch + 1 have the same numerical value But ++ch is type char

and prints as a character, while ch + 1, because it adds a char to an int, is type

int and prints as a number

.3: Consider carefully the following program:

#include <iostream>

using namespace std;

int main() {

char ch;

int ct1, ct2;

ct1 = ct2 = 0;

while ((ch = cin.get()) != '$') {

cout << ch;

ct1++;

if (ch = '$') ct2++;

cout << ch;

} cout <<"ct1 = " << ct1 << ", ct2 = " << ct2 << "\n";

return 0;

} Suppose we provide the following input, where represents pressing Enter:

Hi!

Send $10 or $20 now!

What is the output? (Recall that input is buffered.)

A: Because the program uses ch = '$' instead of ch == '$', the combined input and output looks like this:

Trang 13

H$i$!$

$Send $10 or $20 now!

S$e$n$d$ $ct1 = 9, ct2 = 9

Each character is converted to the $ character before being printed the second time Also, the value of the expression ch = $ is the code for the $ character, hence nonzero, hence true; so ct2 is incremented each time

.4: Construct logical expressions to represent the following conditions:

weight is greater than or equal to 115 but less than 125

a.

ch is q or Q

b.

x is even but is not 26

c.

x is even but is not a multiple of 26

d.

donation is in the range 1000–2000 or guest is 1

e.

ch is a lowercase letter or an uppercase letter (assume the lowercase letters are coded sequentially and that the uppercase letters are coded sequentially but that there is a gap in the code between uppercase and lowercase)

f.

A:

weight >= 115 && weight < 125

a.

ch == 'q' || ch == 'Q'

b.

x % 2 == 0 && x != 26

c.

x % 2 == 0 && !(x % 26 == 0)

d.

donation >= 1000 && donation <= 2000 || guest == 1

e.

Trang 14

(ch >= 'a' && ch <= 'z') ||(ch >= 'A' && ch <= 'Z')

f.

.5: In English the statement "I will not not speak" means the same as "I will speak."

In C++, is !!x the same as x?

A: Not necessarily For example, if x is 10, then !x is 0 and !!x is 1 However, if x is

a bool variable, then !!x is x

.6: Construct a conditional expression that is equal to the absolute value of a variable That is, if a variable x is positive, the value of the expression is just x, but if x is negative, the value of the expression is -x, which is positive

A:

(x < 0)? -x : x or

(x >= 0)? x : -x;

.7: Rewrite the following fragment using switch:

if (ch == 'A') a_grade++;

else if (ch == 'B') b_grade++;

else if (ch == 'C') c_grade++;

else if (ch == 'D') d_grade++;

else f_grade++;

A:

switch (ch) {

Trang 15

case 'A': a_grade++;

break;

case 'B': b_grade++;

break;

case 'C': c_grade++;

break;

case 'D': d_grade++;

break;

default: f_grade++;

break;

}

.8: In Listing 6.10, what advantage would there be in using character labels, such

as a and c, instead of numbers for the menu choices and switch cases? (Hint:

Think about what happens if the user types q in either case and what happens

if the user types 5 in either case.)

A: If you use integer labels and the user types a noninteger such as q, the program hangs up because integer input can't process a character But if you use character labels and the user types an integer such as 5, character input will process 5 as a character Then the default part of the switch can suggest entering another character

.9: Consider the following code fragment:

int line = 0;

char ch;

while (cin.get(ch)) {

if (ch == 'Q') break;

if (ch != '\n') continue;

line++;

}

Trang 16

Rewrite this code without using break or continue.

A: Here is one version:

int line = 0;

char ch;

while (cin.get(ch) && ch != 'Q') {

if (ch == '\n') line++;

}

Chapter 7

.1: What are the three steps in using a function?

A: The three steps are defining the function, providing a prototype, and calling the function

.2: Construct function prototypes that match the following descriptions:

igor() takes no arguments and has no return value

a.

tofu() takes an int argument and returns a float

b.

mpg() takes two type double arguments and returns a double

c.

summation() takes the name of a long array and an array size as values and returns a long value

d.

doctor() takes a string argument (the string is not to be modified) and returns a double value

e.

ofcourse() takes a boss structure as an argument and returns nothing

f.

Ngày đăng: 07/07/2014, 06:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN