Sams Teach Yourself C in 21 Days

(singke) #1
Exploring the C Function Library 537

19


16: printf(“\nCeil: %lf”, ceil(x));
17: printf(“\nFloor: %lf”, floor(x));
18: if( x >= 0 )
19: printf(“\nSquare root: %lf”, sqrt(x) );
20: else
21: printf(“\nNegative number” );
22:
23: printf(“\nCosine: %lf\n”, cos(x));
24: return 0;
25: }

Enter a number: 100.95

Original value: 100.950000
Ceil: 101.000000
Floor: 100.000000
Square root: 10.047388
Cosine: 0.913482
This listing uses just a few of the math functions that are available in the C stan-
dard library. Line 12 inputs a number from the user, which is then printed. Next
this value is passed to four of the C library math functions—ceil(),floor(),sqrt(),
andcos(). Notice that sqrt()is called only if the number isn’t negative because, by
definition, negative numbers don’t have square roots. You can add any of the other math
functions to a program such as this to test its functionality.

Dealing with Time ..............................................................................................


The C library contains several functions that let your program work with times. In C, the
termtimesrefers to dates as well as times. The function prototypes and the definition of
the structure used by many of the time functions are in the header file time.h.

Representing Time ........................................................................................


The C time functions represent time in two ways. The more basic method is the number
of seconds elapsed since midnight on January 1, 1970. Negative values are used to repre-
sent times before that date. These time values are stored as type longintegers. In time.h,
the symbols time_tandclock_tare both defined with a typedefstatement as long.
These symbols are used in the time function prototypes rather than long.
The second method represents a time broken down into its components: year, month,
day, and so on. For this kind of time representation, the time functions use a structure tm,
defined in time.h as follows:

LISTING19.1 continued

INPUT/
OUTPUT

ANALYSIS

30 448201x-CH19 8/13/02 11:20 AM Page 537

Free download pdf