Download PROGRAMMING FUNDAMENTALS IN C++

Transcript
91
Figure 2.19
Realizing the each line in the display can only be produced by executing a cout statement, it should
be clear that four such statements must be executed.
Additionally, since each output line contains three
computed values, each cout statement will have three items in its expression list.
The only input to the program consists of the value of x. This will, of course, require a single prompt
and a cin statement to input the necessary value.
2.3.6.2 Step 2: Develop a Solution
Before any output items can be calculated, the program needs to prompt the user for a value of x and then
accept the entered value. The output display consists of two title lines followed by four lines of calculated
data. The title lines can be produced using two cout statements. Now let's see how the data being displayed
are produced.
The rst item on the rst data output line illustrated in Table 3.4 can be obtained using the exp()
function. The second item on this line, the approximation to ex , can be obtained by using the rst term
in the polynomial that was given in the program specication. Finally, the third item on the line can be
calculated by using the abs() function on the dierence between the rst two lines. When all of these items
are calculated, a single cout statement can be used to display the three results on the same line.
The second output line illustrated in Table 3.4 displays the same type of items as the rst line, except
that the approximation to ex requires the two of two terms of the approximating polynomial. Notice also
that the rst item on the second line, the value obtained by the exp() function, is the same as the rst item
on the rst line. This means that this item does not have to recalculated; the value calculated for the rst
line can simply be displayed a second line. Once the data for the second line have been calculated, a single
cout statement can again be used to display the required values.
Finally, only the second and third items on the last two output lines shown in Figure 1 need to be
recalculated because the rst item on these lines is the same as previously calculated for the rst line. Thus,
for this problem, the complete algorithm described in pseudocode is:
Display a prompt for the input value of x.
Read the input value.
Display the heading lines.
Calculate the exponential value of x using the exp() function.
Calculate the first approximation.
Calculate the first difference.
Print the first output line.
Calculate the second approximation.
Calculate the second difference.