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

Next, let’s try something more ambitious and write a function that converts rectangular coordinates to polar coordinates. We’ll have the function accept a rect structure as its argument and return a polar structure to the calling function. This involves using functions from the math library, so the program has to include the cmath header file (math.h on older systems). Also on some systems you have to tell the compiler to load the math library (see Chapter 1, “Getting Started with C++”). You can use the Pythagorean theorem to get the distance from the horizontal and vertical components:

distance = sqrt( x * x + y * y)

The atan2() function from the math library calculates the angle from the x and y values:

angle = atan2(y, x)

(There’s also an atan() function, but it doesn’t distinguish between angles 180 degrees apart. That uncertainty is no more desirable in a math function than it is in a wilderness guide.)

Given these formulas, you can write the function as follows:

// convert rectangular to polar coordinates

polar rect_to_polar(rect xypos)   // type polar

{

    polar answer;

    answer.distance =

        sqrt( xypos.x * xypos.x + xypos.y * xypos.y);

    answer.angle = atan2(xypos.y, xypos.x);

    return answer;      // returns a polar structure

}

Now that the functions are ready, writing the rest of the program is straightforward. Listing 7.12 presents the result.

Listing 7.12. strctfun.cpp

// strctfun.cpp -- functions with a structure argument

#include

#include

// structure declarations

struct polar

{

    double distance;      // distance from origin

    double angle;         // direction from origin

};

struct rect

{

    double x;             // horizontal distance from origin

    double y;             // vertical distance from origin

};

// prototypes

polar rect_to_polar(rect xypos);

void show_polar(polar dapos);

int main()

{

    using namespace std;

    rect rplace;

    polar pplace;

    cout << "Enter the x and y values: ";

    while (cin >> rplace.x >> rplace.y)  // slick use of cin

    {

        pplace = rect_to_polar(rplace);

        show_polar(pplace);

        cout << "Next two numbers (q to quit): ";

    }

    cout << "Done.\n";

    return 0;

}

// convert rectangular to polar coordinates

polar rect_to_polar(rect xypos)

{

    using namespace std;

    polar answer;

    answer.distance =

        sqrt( xypos.x * xypos.x + xypos.y * xypos.y);

    answer.angle = atan2(xypos.y, xypos.x);

    return answer;      // returns a polar structure

}

// show polar coordinates, converting angle to degrees

void show_polar (polar dapos)

{

    using namespace std;

    const double Rad_to_deg = 57.29577951;

    cout << "distance = " << dapos.distance;

    cout << ", angle = " << dapos.angle * Rad_to_deg;

    cout << " degrees\n";

}

Note

Some compilers require explicit instructions to search the math library. For example, older versions of g++ uses this command line:

g++ structfun.C -lm

Here is a sample run of the program in Listing 7.12:

Enter the x and y values: 30 40

distance = 50, angle = 53.1301 degrees

Next two numbers (q to quit): -100 100

distance = 141.421, angle = 135 degrees

Next two numbers (q to quit): q

Program Notes

We’ve already discussed the two functions in Listing 7.12, so let’s review how the program uses cin to control a while loop:

while (cin >> rplace.x >> rplace.y)

Recall that cin is an object of the istream class. The extraction operator (>>) is designed in such a way that cin >> rplace.x also is an object of that type. As you’ll see in Chapter 11, “Working with Classes,” class operators are implemented with functions. What really happens when you use cin >> rplace.x is that the program calls a function that returns a type istream value. If you apply the extraction operator to the cin >> rplace.x object (as in cin >> rplace.x >> rplace.y), you again get an object of the istream class. Thus, the entire while loop test expression eventually evaluates to cin, which, as you may recall, when used in the context of a test expression, is converted to a bool value of true or false, depending on whether input succeeded. In the loop in Listing 7.12, for example, cin expects the user to enter two numbers. If, instead, the user enters q, as shown in the sample output, cin >> recognizes that q is not a number. It leaves the q in the input queue and returns a value that’s converted to false, terminating the loop.

Compare that approach for reading numbers to this simpler one:

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

{

    cout << "Enter value #" << (i + 1) << ": ";

    cin >> temp;

    if (temp < 0)

        break;

    ar[i] = temp;

}

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

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

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

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