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

A wise choice ... bye

The program reads just one character, so only the first character in the response matters. That means the user could have input NO! instead of N. The program would just read the N. But if the program tried to read more input later, it would start at the O.

The Logical AND Operator: &&

The logical AND operator, written &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expressions are true. Here are some examples:

5 == 5 && 4 == 4   // true because both expressions are true

5 == 3 && 4 == 4   // false because first expression is false

5 > 3 && 5 > 10    // false because second expression is false

5 > 8 && 5 < 10    // false because first expression is false

5 < 8 && 5 > 2     // true because both expressions are true

5 > 8 && 5 < 2     // false because both expressions are false

Because the && has a lower precedence than the relational operators, you don’t need to use parentheses in these expressions. Like the || operator, the && operator acts as a sequence point, so the left side is evaluated, and any side effects are carried out before the right side is evaluated. If the left side is false, the whole logical expression must be false, so C++ doesn’t bother evaluating the right side in that case. Table 6.2 summarizes how the && operator works.

Table 6.2. The && Operator

Listing 6.5 shows how to use && to cope with a common situation, terminating a while loop, for two different reasons. In the listing, a while loop reads values into an array. One test (i < ArSize) terminates the loop when the array is full. The second test (temp >= 0) gives the user the option of quitting early by entering a negative number. The program uses the && operator to combine the two tests into a single condition. The program also uses two if statements, an if else statement, and a for loop, so it demonstrates several topics from this chapter and Chapter 5.

Listing 6.5. and.cpp

// and.cpp -- using the logical AND operator

#include

const int ArSize = 6;

int main()

{

    using namespace std;

    float naaq[ArSize];

    cout << "Enter the NAAQs (New Age Awareness Quotients) "

         << "of\nyour neighbors. Program terminates "

         << "when you make\n" << ArSize << " entries "

         << "or enter a negative value.\n";

    int i = 0;

    float temp;

    cout << "First value: ";

    cin >> temp;

    while (i < ArSize && temp >= 0) // 2 quitting criteria

    {

        naaq[i] = temp;

        ++i;

        if (i < ArSize)             // room left in the array,

        {

            cout << "Next value: ";

            cin >> temp;            // so get next value

        }

    }

    if (i == 0)

        cout << "No data--bye\n";

    else

    {

        cout << "Enter your NAAQ: ";

        float you;

        cin >> you;

        int count = 0;

        for (int j = 0; j < i; j++)

            if (naaq[j] > you)

                ++count;

        cout << count;

        cout << " of your neighbors have greater awareness of\n"

             << "the New Age than you do.\n";

    }

    return 0;

}

Note that the program in Listing 6.5 places input into the temporary variable temp. Only after it verifies that the input is valid does the program assign the value to the array.

Here are a couple of sample runs of the program. One terminates after six entries:

Enter the NAAQs (New Age Awareness Quotients) of

your neighbors. Program terminates when you make

6 entries or enter a negative value.

First value: 28

Next value: 72

Next value: 15

Next value: 6

Next value: 130

Next value: 145

Enter your NAAQ: 50

3 of your neighbors have greater awareness of

the New Age than you do.

The second run terminates after a negative value is entered:

Enter the NAAQs (New Age Awareness Quotients) of

your neighbors. Program terminates when you make

6 entries or enter a negative value.

First value: 123

Next value: 119

Next value: 4

Next value: 89

Next value: -1

Enter your NAAQ: 123.031

0 of your neighbors have greater awareness of

the New Age than you do.

Program Notes

The following is the input part of the program in Listing 6.5:

cin >> temp;

while (i < ArSize && temp >= 0) // 2 quitting criteria

{

    naaq[i] = temp;

    ++i;

    if (i < ArSize)             // room left in the array,

    {

        cout << "Next value: ";

        cin >> temp;            // so get next value

    }

}

The program begins by reading the first input value into a temporary variable called temp. Then the while test condition checks whether there is still room left in the array (i < ArSize) and whether the input value is non-negative (temp >= 0). If it is, the program copies the temp value to the array and increases the array index by one. At that point, because array numbering starts at zero, i equals the total number of entries to date. That is, if i starts out at 0, the first cycle through the loop assigns a value to naaq[0] and then sets i to 1.

The loop terminates when the array is filled or when the user enters a negative number. Note that the loop reads another value into temp only if i is less than ArSize—that is, only if there is still room left in the array.

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

Все книги серии 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.

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

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