Home Practices Page 11 - Basic Data Types and Calculations

# Try It Out: Yet More Output Manipulators - Practices

This article looks at some of the basic data types that are built into C++. If you're learning how to use C++, you will want to keep reading, since you'll be using these data types in all of your programs. It is taken from chapter two of the book Beginning ANSI C++: The Complete Language, by Ivor Horton (Apress, 2004; ISBN: 1590592271).

Rating:  / 14
September 08, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE
 advertisement

Here’s the same code as in the previous “Try It Out” exercise, except that it uses additional manipulators to improve the appearance of the output:

// Program 2.8 Experimenting with floating point output

#include#includeusing std::setprecision; using std::fixed; using std::scientific;

using std::cout; using std::endl;

int main() { float value1 = 0.1f; float value2 = 2.1f; value1 -= 0.09f; value2 -= 2.09f;

cout << setprecision(14) << fixed;

cout << value1 - value2 << endl;

cout << setprecision(5) << scientific; cout << value1 - value2 << endl;

return 0; } // Should be 0.01

// Should be 0.01

// Change to fixed notation

// Should output zero

// Set scientific notation // Should output zero

When I run the modified program, this is the output I get:

0.00000000745058 7.45058e-009

(Continued)

This code uses three new manipulators. Thesetprecision()manipulator specifies how many decimal places should appear after the decimal point when you’re outputting a floating-point number. Thefixedandscientificmanipulators complement one another and choose the format in which a floating-point number should be displayed when they’re written to the stream.

By default, your C++ compiler will select eitherscientificorfixed, depending on the particular value you’re outputting, and you saw in the first version of this program that it performed that task admirably. The default number of decimal places isn’t defined in the standard, but five is common.

Let’s look at the changes made. Apart from the#includefor, just as you needed when you were usingsetw()earlier in the chapter and the additionalusingdeclarations, the interest is in these four lines of code:

 cout << setprecision(14) << fixed; // Change to fixed notation cout << value1 - value2 << endl; // Should output zero cout << setprecision(5) << scientific; // Set scientific notation cout << value1 - value2 << endl; // Should output zero

The first line is easy: you use the manipulators like you usedsetw(), by sending them to the output stream with the insertion operator. Their effects can then clearly be seen in the first line of output: you get a floating-point value with 14 decimal places and no exponent.

Note that these manipulators differ fromsetw()in that they’re modal.In other words, they remain in effect for the stream until the end of the program, unless you set a different option. That’s the reason for the third line in the preceding code—you have to set scientific mode and a precision of 5 explicitly in order to return to “default” behavior. You can see that you’ve succeeded, though, because the second line of output is the same as the one produced by the original program.

NOTE Actually, the header is only required here for the setprecision()manipulator. Both fixedand scientificare defined in . There are more manipulators to discuss, but the rule is that the ones requiring values (such as setw()and setprecision()) are defined in , whereas the others are defined in .

Mathematical Functions

Thestandard library header defines a range of trigonometric and numerical functions that you can use in your programs. You’ve already seen thesqrt()function. Table 2-11 presents some other numerical functions from this header that you may find useful.

Table 2-11.Numerical Functions

Function

abs(arg)

fabs(arg) ceil(arg)

floor(arg)

exp(arg) log(arg) log10(arg) pow(arg1, arg2)

Description

Returns the absolute value of arg as the same type asarg, whereargcan be of any floating-point type. There are versions of theabs()function declared in theheader file for arguments of typeintand typelong.

as the same type as arg , where ar g can be of any floating-point type. There are versions of the abs() function declared in the header file for arguments of typ e int and type long.arg as the same type as arg , where ar g can be of any floating-point type. There are versions of the abs() function declared in the header file for arguments of typ e int and type long.Returns the absolute value of arg as the same type as arg, where arg can be of any floating-point type. There are versions of the abs() function declared in the header file for arguments of type int and type long.

Returns the absolute value ofargas the same type as the argument.

The argument can beint,long,float,double, orlong double.Returns a floating-point value of the same type asargthat is the smallest integer greater than or equal toarg, soceil(2.5)produces the value 3.0.argcan be of any floating-point type.

Returns a floating-point value of the same type asargthat is the largest integer less than or equal toargso the value returned byfloor(2.5)will be 2.0.argcan be of any floating-point type.

Returns the value ofearg as the same type asarg.argcan be of any

floating-point type. Thelogfunction returns the natural logarithm (to base e) ofargas the same type asarg.argcan be any floating-point type.

Thelog10function returns the logarithm to base 10 ofargas the same

type asarg.argcan be any floating-point type. Thepowfunction returns the value ofarg1raised to the powerarg1,which is arg1arg2. Thus the result ofpow(2, 3)will be 8, and the result ofpow(1.5, 3)will be 3.375. The arguments can be both of typeintor any floating-point type. The second argument,arg2, may also be of typeintwitharg1of typeint, orlong, or any floating-point type. The value returned will be of the same type asarg1.

Table 2-12 shows the trigonometric functions that you have available in theheader.

 Function Description cos(angle) Returns the cosine of the angle expressed in radians that is passed as the argument. sin(angle) Returns the sine of the angle expressed in radians that is passed as the argument. tan(angle) Returns the tangent of the angle expressed in radians that is passed as the argument. cosh(angle) Returns the hyperbolic cosine of the angle expressed in radians that is passed as the argument. The hyperbolic cosine of a variable x is given by formula (ex-e-x)/2. sinh(angle) Returns the hyperbolic sine of the angle expressed in radians that is passed as the argument. The hyperbolic sine of a variable x is given by the formula (ex+e-x)/2. tanh(angle) Returns the hyperbolic tangent of the angle expressed in radians that is passed as the argument. The hyberbolic tangent of a variable x is given by the hyperbolic sine of x divided by the hyperbolic cosine of x. acos(arg) Returns the inverse cosine (arccosine) ofarg. The argument must be between –1 and +1. The result is in radians and will be from 0 to p. asin(arg) Returns the inverse sine (arcsine) of the argument. The argument must be between –1 and +1. The result is in radians and will be from –p/2 to +p/2. atan(arg) Returns the inverse tangent (arctangent) of the argument. The result is in radians and will be from –p/2 to +p/2. atan2(arg1, arg2) This function requires two arguments of the same floating-point type. The function returns the inverse tangent ofarg1/arg2. The result will be in the range from –p to +p radians and of the same type as the arguments.

The arguments to these functions can be of any floating-point type and the result will be returned as the same type as the argument(s).

Let’s look at some examples of how these are used. Here’s how you can calculate the sine of an angle in radians:

double angle = 1.5; // In radians double sine_value = std::sin(angle);

If the angle is in degrees, you can calculate the tangent by using a value for p to convert to radians:

float angle_deg = 60.0f; // Angle in degrees const float pi = 1.14159f; const float pi_degrees = 180.0f; float tangent = std::tan(pi*angle_deg/pi_degrees);

If you know the height of the church steeple is 100 feet and you’re standing 50 feet from the base of the steeple, you can calculate the angle in radians of the top of the

steeple like this:
double height = 100.0; // Steeple height- feet
double distance = 50.0; // Distance from base
angle = std::atan2(height, distance); // Result in radians

You can use this value inangleand the value ofdistanceto calculate the distance from your toe to the top of the steeple:

double toe_to_tip = distance*std::cos(angle);

Of course, fans of Pythagoras of Samos could obtain the result much more easily, like this:

double toe_to_tip = std::sqrt(std::pow(distance,2) + std::pow(height, 2);

 >>> More Practices Articles          >>> More By Apress Publishing

blog comments powered by Disqus

© 2003-2014 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap