Читаем C++ Primer Plus полностью

cout.put(char(88));         // put() prints char as character

cout << char(88) << endl;    // new-style type cast value to char

cout << (char)88 << endl;    // old-style type cast value to char

7. 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. The long long type, on the other hand, can reach 19 digits, which exceeds the 13 significant figures guaranteed for double.

8.

a. 8 * 9 + 2 is 72 + 2 is 74

b. 6 * 3 / 4 is 18 / 4 is 4

c. 3 / 4 * 6 is 0 * 6 is 0

d. 6.0 * 3 / 4 is 18.0 / 4 is 4.5

e. 15 % 4 is 3

9. Either of the following would work for the first task:

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

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

To add them as type double and then convert, you could do either of the following:

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

int pos = int(x1 + x2);

10.

a. int

b. float

c. char

d. char32_t

e. double

Answers to Chapter Review for Chapter 4

1.

a. char actors[30];

b. short betsie[100];

c. float chuck[13];

d. long double dipsea[64];

2.

a. array actors;

b. array betsie;

c. array chuck;

d. array dipsea;

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

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

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

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

or

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

7. string lunch = "Waldorf Salad";

or, if you don’t have a using directive,

std::string lunch = "Waldorf Salad";

8.

struct fish {

    char kind[20];

    int weight;

    float length;

};

9.

fish petes =

{

    "trout",

    12,

    26.25

};

10. enum Response {No, Yes, Maybe};

11.

double * pd = &ted

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

12.

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

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

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

13. This assumes that the iostream and vector header files have been included and that there is a using directive:

unsigned int size;

cout << "Enter a positive integer: ";

cin >> size;

int * dyn = new int [size];

vector dv(size);

14. 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, assuming the int type is wide enough to hold an address.

15.

struct fish

{

    char kind[20];

    int weight;

    float length;

};

fish * pole = new fish;

cout << "Enter kind of fish: ";

cin >> pole->kind;

16. 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.

17.

#include

#include

#include

const int Str_num {10};  // or = 10

...

std::vector vstr(Str_num);

std::array astr;

Answers to Chapter Review for Chapter 5

1. An entry-condition loop evaluates a test expression before entering the body of the loop. If the condition is initially 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 is initially false. The for and while loops are entry-condition loops, and the do while loop is an exit-condition loop.

2. It would print the following:

01234

Note that cout << endl; is not part of the loop body (because there are no braces).

3. It would print the following:

0369

12

4. It would print the following:

6

8

5. It would print the following:

k = 8

6. It’s simplest to use the *= operator:

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

    cout << num << " ";

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

8. 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 is also 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. The cin >> ch form skips over spaces, newlines, and tabs when it encounters them. The other two forms read those characters.

Answers to Chapter Review for Chapter 6

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных