Chapter 15 - Power Programming: Tapping Important C and C++ Libraries
Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
Copyright 1998 The McGraw-Hill Companies
The Math Functions (MATH.H)
The functions prototyped in the MATH.H header file permit a great variety of mathematical, algebraic, and trigonometric operations.
The math functions are relatively easy to use and to understand for those familiar with algebraic and trigonometric concepts. The most popular math functions are shown in Table 15-10.
Table 15-10: Popular Math Functions
Function
Description
abs( )
Returns absolute value of integer argument
acos( ), acosl( )
Arc cosine
asin( ), asinl( )
Arc sine
atan( ), atanl( )
Arc tangent
atan2( ), atan2l( )
Arc tangent of two numbers
ceil( ), ceill( )
Greatest integer
cos( ), cosl( )
Cosine
cosh( ), coshl( )
Hyberbolic cosine
exp( ), expl( )
Exponential value
fabs( ), fabsl( )
Absolute value
floor( ), floorl( )
Smallest value
fmod( ), fmodl( )
Modulus operator
frexp( ), frexpl( )
Split mantissa and exponent
hypot( ), hypotl( )
Hypotenuse
labs( )
Returns absolute value of long argument
ldexp( ), ldexpl( )
x times 2 to the exp power
log( ), logl( )
Natural log
log10( ), log10l( )
Common log
modf( ), modfl( )
Mantissa and exponent
pow( ), powl( )
x to y power
pow10( ), pow10l( )
x raised by power of 10
sin( ), sinl( )
Sine
sinh( ), sinhl( )
Hyperbolic sine
sqrt( ), sqrtl( )
Square root
tan( ), tanl( )
Tangent
tanh( ), tanhl( )
Hyperbolic tangent
Note
Functions accept and return double values except where noted.
Note
Functions ending in “l” accept and return longdouble values.
Many of these functions were demonstrated in earlier chapters. When using trigonometric functions, remember that angle arguments are always specified in radians.
Programmers desiring complex number arithmetic must resort to using struct complex and the _cabs( ) function described in MATH.H. Following is the only structure available for complex arithmetic in Visual C++:
struct complex {double x,double y}
This structure is used by the _cabs( ) function. The _cabs( ) function returns the absolute value of a complex number.
Building a Table of Trigonometric Values
Since math functions have already been used extensively in this book, the only example for this section involves an application that will generate a table of sine, cosine, and tangent values for the angles from zero to 45 degrees.
This application also takes advantage of the special C++ formatting abilities. Study the following listing to determine how the output will be sent to the screen:
// // math.cpp // A program that demonstrates the use of several // math functions. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
for (i=0;i<=45;i++) { ang=PI*i/180; // convert degrees to radians x=sin(ang); y=cos(ang); z=tan(ang); // formatting output columns cout << setiosflags(ios::left) << setw(8) << setiosflags(ios::fixed) << setprecision(6); // data to print cout << i << “\t” << x << “\t” << y << “\t” << z << “\n”; } return (0); }
This application uses the sin( ), cos( ), and tan( ) functions to produce a formatted trigonometric table. The angles are stepped from zero to 45 degrees and are converted to radians before being sent to each function. This particular C++ formatting is discussed in more detail in Chapter 18.
Following is a partial output from this application:
Table 15-11 shows some of the time and date function found in TIME.H.
Table 15-11: Time and Date Functions
Names
Description
asctime( )
Converts date and time to an ASCII string and uses tm structure
ctime( )
Converts date and time to a string
difftime( )
Calculates the difference between two times
gmtime( )
Converts date and time to GMT using tm structure
localtime( )
Converts date and time to tm structure
strftime( )
Allows formatting of date and time data for output
time( )
Obtains current time (system)
tzset( )
Sets time variables for environment variable TZ
These functions offer a variety of ways to obtain time and/or date formats for programs. A discussion of the syntax for each function is included in the next section.
Time and Date Structures and Syntax
Many of the date and time functions described in the previous section use the tm structure defined in TIME.H. This structure is shown here:
struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; };
The syntax for calling each date and time function differs according to the function’s ability. The syntax and parameters for each function are shown in Table 15-12.
Table 15-12: Time and Date Function Parameters
Function
Description
char * ASCTIME(CONST STRUCT tm * tblock)
Converts the structure into a 26-character string
For example: Sun June 1, 10:18:20 1998\n\0
char * CTIME(CONST TIME_T *time)
Converts a time value, pointed to by * time into a 26-char string (see asctime( ))
double difftime(time_t time2, time_t time1)
Calculates the difference between time2 and time1 and returns a double
struct tm * GMTIME(CONST TIME_T * TIMER)
Accepts address of a value returned by the function time( ) and returns a pointer to the structure with GMT information
struct tm * LOCALTIME(CONST TIME_T * TIMER)
Accepts address of a value returned by the function time( ) and returns a pointer to the structure with local time information
Formats date and time information for output. s points to the string information, maxsize is maximum string length, fmt represents the format, and t points to a structure of type tm. The formatting options include:
%a Abbreviate weekday name
%A Full weekday name
%b Abbreviate month name
%B Full month name
%c Date and time information
%d Day of month (01 to 31)
%H Hour (00 to 23)
%I Hour (00 to 12)
%j Day of year (001 to 366)
%m Month (01 to 12)
%M Minutes (00 to 59)
%p AM or PM
%S Seconds (0 to 59)
%U Week number (00 to 51), Sunday is first day
%w Weekday (0 to 6)
%W Week number (00 to 51), Monday is first day
%x Date
%X Time
%y Year, without century (00 to 99)
%Y Year, with century
%Z Time zone name
%% Character %
time_t time(time_t *timer)
Returns the time in seconds since 00:00:00 GMT, January 1, 1998
void _tzset (void)
Sets the global variables daylight, timezone0, and tzname0 based on the environment string
The TZ environment string uses the following syntax:
TZ = zzz[+/-]d[d]{lll}
Here, zzz represents a three-character string with the local time zone—for example, “EST” for eastern standard time. The [+/]d[d] argument contains an adjustment for the local time zone’s difference from GMT. Positive numbers are a westward adjustment, while negative numbers are an eastward adjustment. For example, a five (5) would be used for EST. The last argument, {lll}, represents the local time zone’s daylight savings time—for example, EDT for eastern daylight savings time.
Several of these functions are used in example programs in the next section.
Working with the localtime( ) and asctime( ) Functions
Many times it is necessary to obtain the time and date in a programming application. The next program returns these values by using the localtime( ) and asctime( ) functions:
/* * asctim.c * Demonstrating the use of the localtime( ) and asctime( ) * functions. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
printf(“The present date and time is: %s\n”, asctime(date_time)); return (0); }
This program formats the time and date information in the manner shown here:
The present date and time is: Sat May 31 13:16:20 1998
Working with the gmtime( ) and asctime( ) Functions
There are other functions that you can also use to return time and date information. The next program is similar to the last example, except that the gmtime( ) function is used.
/* * cmtime.c * Demonstrating the use of the gmtime( ) and asctime( ) * functions. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
The following date and time information was returned by this program:
Sat May 31 14:13:25
Working with the strftime( ) Function
The strftime( ) function provides the greatest formatting flexibility of all the date and time functions. The following program illustrates several formatting options.
/* * strtm.c * Demonstrating the use of the strftime( ) function. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
time(&timer); date_time=localtime(&timer); strftime(str,80,"It is %X on %A, %x", date_time); printf(“%s\n”,str); return (0); }
Here is a sample of the output for this program:
It is 17:18:45 on Saturday, 05/31/98
You may find that the strftime( ) function is not portable from one system to another. Use it with caution if portability is a consideration.
Working with the ctime( ) Function
The following C++ program illustrates how to make a call to the ctime( ) function. This program shows how easy it is to obtain date and time information from the system.
// // ctime.cpp // Demonstrating the use of the ctime( ) function. // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
#include <time.h> #include <iostream.h>
time_t longtime;
main( ) { time(&longtime); cout << “The time and date are ” << ctime(&longtime) << “\n”; return (0); }
The output, sent to the screen, would appear in the following format:
The time and date are Sat May 31 14:23:27 1998
Creating a Time Delay Routine
Usually it is desirable for programs to execute as quickly as possible. However, there are times when slowing down information makes it easier for the user to view and understand. The time_delay( ) function in the following application delays program execution. The delay variable is in seconds. For this example, there is a two-second delay between each line of output to the screen.
/* * tdelay.c * A C program that demonstrates how to create a delay * function for slowing program output. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdio.h> #include <time.h>
void time_delay(int);
main( ) { int i;
for (i=0;i<25;i++) { time_delay(2); printf(“The count is %d\n”,i); } return (0); }
void time_delay(int t) { long initial,final; long ltime;
initial=time(<ime); final=initial+t;
while (time(<ime) < final); return; }
What other uses might the time_delay( ) function have? One case might be where the computer is connected to an external data-sensing device, such as a thermocouple or strain gauge. The function could be used to take readings every minute, hour, or day.