Title: Distance Learning Center
1Distance Learning Center
- Lecture 10
- C Programming Language with Applications
- Melissa Lin, IT Consultant
- HenEm, Inc. Parkville, Missouri
- linm_at_ipfw.edu
- http//www.etcs.ipfw.edu/linm
2Lecture 10 - C Standard Library Functions
- C Standard Library
- Standard Math library ltmath.hgt
- Standard Math Function Prototype
- Examples Using math.h
- Example 10-1 Using Trigonometry Functions
sin(), cos(), and tan() - Ceiling and Floor Functions
- Trigonometry and Inverse Trigonometric Functions
- Hyperbolic Functions
- Logarithm Functions
3Lecture 10 - C Standard Library Functions
(continue)
- Power and Square Functions
- Example 10-2 Testing Math Functions 1
- Example 10-3 Testing More Math Functions and
Program Documentation - Standard Utility Library ltsdtlib.hgt
- Random Number Generation Functions
- Examples Using stdlib.h
- Example 10-4 Using Random Number Generation
Function - Example 10-5 A Program for Rolling Two Dices
- Summary
4The C Standard Library
- Standard C functions, types, and macros of the
standard library are declared in standard header
files. - Headers can be accessed by include ltheadergt
- Headers must be included outside of any external
declaration before the use of any C functions. - The standard headers are ltassert.hgt, ltctype.hgt,
lterrno.hgt, ltfloat.hgt, ltlimit.hgt, ltlocal.hgt,
ltmath.hgt, ltsetjmp.hgt, ltsignal.hgt, ltstdarg.hgt,
ltstddef.hgt, ltstdio.hgt, ltstdlib.hgt, ltstring.hgt,
and lttime.hgt - Will discuss only ltstdio.hgt, ltmath.hgt,
ltstdlib.hgt, lt.limit.hgt, and ltfloat.hgt
5Standard Math Function Prototype
- ltmath.hgt - the header file of mathematical
functions that declare mathematical functions and
macros - The C standard mathematics functions, ltmath.hgt,
must be included in the C program when using math
functions - All functions in ltmath.hgt allow the programmer to
perform certain common mathematical calculations.
6Standard Math Function Prototype (continue)
- All the input arguments and return value from a
math function are defined as double
floating-point number data type by default - The argument for trigonometric functions should
be in the units of radians. - Conversion formula
- Angle_radian angle_degree (PI/180), where PI
is 3.1416159. - Math function prototype and definition
7Standard Math Functions Prototype (continue)
- Standard math functions available for use through
header file inclusion include ltmath.hgt are - sin(x) sine of x
- cos(x) cosine of x
- tan(x) tangent of x
- pow(x, y) x goes to power of y, xy
- sqrt(x) square root of x
- exp(x) exponential function ex
- log(x) natural logarithm of x (base e)
- ceil(x) round x to the smallest number
not less than x - floor(x) round x to the largest number not
greater than x - And more.
8Example 10-1 Using Trigonometry Functions
sin(), cos(), and tan()
- Problem Statement
- Write a simple C program to explain how to use
trigonometry functions sin(), cos(), and tan()
functions. - Analysis and Requirements
- Two symbolic constants are defined using the
identity 360? 2? radians - define variable as double floating-point number
type - examine the program output by print them using
the 1f format specifier for double type.
9Example 10-1 Using Trigonometry Functions
sin(), cos(), and tan() (continue)
- / trigomath.c /
- include ltmath.hgt
- include ltstdio.hgt
- define PI 3.14159
- define Deg_to_Rad PI/180.0
- define Rad_to_Deg 180.0/PI
- void main(void)
-
- double theta 45.0
- double ysin, ycos, ytan
- ysin sin(theta Deg_to_Rad)
- //theta Deg_to_Rad 45.0 PI/180.0
- // 45.0 3.14159/180.0 0.785397
- // ysin sin(theta Deg_to_Rad)
sin(0.7853975)
10Example 10-1 Using Trigonometry Functions
sin(), cos(), and tan() (continue)
- ycos cos(theta Deg_to_Rad)
- ytan tan(theta Deg_to_Rad)
- printf("sin(lf Degree) lf\n", theta, ysin)
- printf("cos(lf Degree) lf\n", theta, ycos)
- printf("tan(lf Degree) lf\n", theta, ytan)
- printf("tan(lf Degree) e\n", theta, ytan)
11Example 10-1 (continue)
- Program Output
- sin(45.000000 Degree) 0.707106
- cos(45.000000 Degree) 0.707107
- tan(45.000000 Degree) 0.999999
- tan(45.000000 Degree) 9.999987e-001
12Ceiling and Floor Functions
- double ceil(double x)
- Calculate the ceiling of a value
- returns a smallest integer that is greater than
or equal to x. - It round up the digits after the decimal points
- Use ceil(x-0.5) to increase accuracy
- double floor(double x)
- returns a largest integer that is less than or
equal to x. - It round off the digits after the decimal points
- Use floor(x 0.5) to increase accuracy
13Trigonometric and Inverse Trigonometric Functions
- double cos(double x)
- Cosine function takes the x in radians
- The result is a value in the range 1.0 to 1.0
- double sin(double x)
- Sine function takes x in radians
- The result is a value in the range 1.0 to 1.0
- double tan(double x)
- Tangent function takes x in radians
- The result is a value in the range 1.0 to 1.0
14Trigonometric and Inverse Trigonometric Functions
(continue)
- double acos(double x)
- Arc cosine function accepts x in the range 1 to
1 - The result is an angle with value between 0 to ?
- double asin(double x)
- Arc sine function accepts x in the range 1 to 1
- The result is an angle with value between -?/2 to
?/2 - double atan(double x)
- Arc tangent function accepts x in the range 1 to
1 - The result is an angle with value between -?/2 to
?/2 - If x is 0, atan() returns 0
- double atan2(double y, double x)
- The function accepts the argument in the form of
y/x. - If both y and x parameters are 0, the result is 0
- The result is an angle with value between -? to ?
15Hyperbolic Functions
- A special class of exponential functions
- double cosh(double x)
- Hyperbolic cosine
- cosh x (ex e-x)/2
- double sinh(double x)
- Hyperbolic sine
- sinh x (ex - e-x)/2
- double tanh(double x)
- Hyperbolic tangent
- tanh x sinh x/ cos hx
16Logarithm Functions
- double log(double x)
- logex
- Calculate natural logarithm, of a positive x if
x is negative it returns a NaN (not a number or
infinite) - double log10(double x)
- log10x
- Compute logarithm to the base 10 of a positive x
17Power and Square Root Functions
- double sqrt(double x)
- Square root of a nonnegative x or x1/2
- double pow(double x, double y)
- Calculate x to the y power or xy
- double exp(double x)
- Raise e (2.718281828..) to the power of x or ex
18Example 10-2 Testing Math Function 1
- / logex.c - Write a program to test various
math functions/ - include ltmath.hgt
- include ltstdio.hgt
- define PI 3.14159
- void main(void)
-
- double y
- printf("log10(1000.0) lf\n", log10(1000.0))
- printf("log(1000.0) lf\n", log(1000.0))
- printf("exp(1) lf\n", exp(1))
19Example 10-2 Testing Math Function 1 (continue)
- printf("pow(2,16) 8.0lf\n", pow(2.0, 16.0))
- printf("sqrt(9) lf\n", sqrt(9.0))
- printf("ceil(99.9999) lf\n",
ceil(99.9999)) - printf("ceil(99.4) lf\n", ceil(99.4))
- printf("ceil(99.0001) lf\n", ceil(99.0001))
- printf("floor(99.9999) lf\n",
floor(99.9999)) - printf("floor(99.4) lf\n", floor(99.4))
- printf("floor(99.0001) lf\n",
floor(99.0001))
20Example 10-2 Testing Math Function 1 (continue)
- Output
- log10(1000.0) 3.000000
- log(1000.0) 6.907755
- exp(1) 2.718282
- pow(2,16) 65536
- sqrt(9) 3.000000
- ceil(99.9999) 100.000000
- ceil(99.4) 100.000000
- ceil(99.0001) 100.000000
- floor(99.9999) 99.000000
- floor(99.4) 99.000000
- floor(99.0001) 99.000000
21Example 10 3 Testing More Math Functions and
Program Documentation
- Problem Statement
- As a technical staff, you are asked to test the
following math functions and report your finding
to other technical staff in your group. - The functions that will be tested are sqrt(),
exp(), log(), log10(), fabs(), ceil(), floor(),
pow(), fmod(), sin(), cos(), and tan()
22Example 10 3 Testing More Math Functions and
Program Documentation (cont.)
- Analysis
- We should study the problem statement in details,
and should ask at least one additional question
for clarification - What is the testing environment? Microsoft Visual
Studio.NET running under Windows XP, Windows
2003, Windows 2000, Linux, etc - We should also have a copy of technical info that
describes function prototypes. The C Programming
Language book by Ritche should be a good desk
reference. - We need to study the functions under testing
sqrt(), exp(), log(), log10(), fabs(), ceil(),
floor(), pow(), fmod(), sin(), cos(), and tan()
23Example 10 3 Testing More Math Functions and
Program Documentation (cont.)
- / ex05_03.c /
- / Testing the math library functions /
- include ltstdio.hgt
- include ltmath.hgt
- / function main begins program execution /
- int main()
-
- / calculates and outputs the square root /
- printf( "sqrt(.1f) .1f\n", 900.0, sqrt(
900.0 ) ) - printf( "sqrt(.1f) .1f\n", 9.0, sqrt( 9.0
) ) -
- / calculates and outputs the exponential
function e to the x / - printf( "exp(.1f) f\n", 1.0, exp( 1.0 ) )
- printf( "exp(.1f) f\n", 2.0, exp( 2.0 ) )
24Example 10 3 Testing More Math Functions and
Program Documentation (cont.)
- / calculates and outputs the logarithm (base
e) / - printf( "log(f) .1f\n", 2.718282, log(
2.718282 ) ) - printf( "log(f) .1f\n", 7.389056, log(
7.389056 ) ) -
- / calculates and outputs the logarithm (base
10) / - printf( "log10(.1f) .1f\n", 1.0, log10(
1.0 ) ) - printf( "log10(.1f) .1f\n", 10.0, log10(
10.0 ) ) - printf( "log10(.1f) .1f\n", 100.0, log10(
100.0 ) ) -
- / calculates and outputs the absolute value
/ - printf( "fabs(.1f) .1f\n", 13.5, fabs(
13.5 ) ) - printf( "fabs(.1f) .1f\n", 0.0, fabs( 0.0
) ) - printf( "fabs(.1f) .1f\n", -13.5, fabs(
-13.5 ) )
25Example 10 3 Testing More Math Functions and
Program Documentation (cont.)
- / calculates and outputs ceil( x ) /
- printf( "ceil(.1f) .1f\n", 9.2, ceil( 9.2
) ) - printf( "ceil(.1f) .1f\n", -9.8, ceil(
-9.8 ) ) -
- / calculates and outputs floor( x ) /
- printf( "floor(.1f) .1f\n", 9.2, floor(
9.2 ) ) - printf( "floor(.1f) .1f\n", -9.8, floor(
-9.8 ) ) -
- / calculates and outputs pow( x, y ) /
- printf( "pow(.1f, .1f) .1f\n", 2.0, 7.0,
pow( 2.0, 7.0 ) ) - printf( "pow(.1f, .1f) .1f\n", 9.0, 0.5,
pow( 9.0, 0.5 ) ) -
- / calculates and outputs fmod( x, y ) /
- printf( "fmod(.3f/.3f) .3f\n", 13.675,
2.333, - fmod( 13.675, 2.333 ) )
26Example 10 3 Testing More Math Functions and
Program Documentation (cont.)
- / calculates and outputs sin( x ) /
- printf( "sin(.1f) .1f\n", 0.0, sin( 0.0 )
) -
- / calculates and outputs cos( x ) /
- printf( "cos(.1f) .1f\n", 0.0, cos( 0.0 )
) -
- / calculates and outputs tan( x ) /
- printf( "tan(.1f) .1f\n", 0.0, tan( 0.0 )
) -
- return 0 / indicates successful termination
/ - / end main /
27Example 10 3 Testing More Math Functions and
Program Documentation
28Example 10-3 Program Documentation
- /
/ - / Program Name ex5-03.c /
- / Programmer M Lin /
- / Date June 20, 2004
/ - / Version 1.0
/ - / Description
/ - / This program tests the following math
functions sqrt(), exp(), / - / log(), log10(), fabs(), ceil(), floor(),
pow(), fmod(), sin(), cos(), / - / and tan(). The Windows Visual Studio.NET
running under / - / Windows XP was used to prepare testing source
code, and / - / ran testing cases
/ - /
/ - / Testing Results
/ - / COPY YOUR TESTING RESULT HERE
/ - /
/
29Utility Function Prototypes
- ltstdlib.hgt - the standard library header file
which declares utility functions for number
conversion, storage allocation, random number
generation, absolute value, etc. - Absolute Value Calculation ltstdlib.hgt
- Int abs(int x)
- // Computes absolute value of an integer value
- long labs(long x)
- // Computes absolute value of a long integer
value - double fabs(double x)
- // Compute absolute value of double float type
value
30Utility Function Prototypes (continue)
- ASCII strings to Numerical Value Conversion
ltstdlib.hgt - double atof(const char string)
- - Convert ASCII string to float-point number
- int atoi(const char string)
- - Convert ASCII string to integer number
- long atol(const char string)
- - Convert ASCII string to long integer
31Random Number Generator Functions
- Random Number Generator Functions - in
ltstdlib.hgt, the standard library function - The range of the value of rand function is
between 0 and RAND_MAX that is at least 32767,
which is the maximum value for a two-byte (i.e.
16 bit) integer. - Example
- rand() 6
- Using the remainder operator () in conjunction
with rand function to produce integers in the
range 0 to 5.
32Random Number Generator Functions (continue)
- include ltstdlib.hgt
- int rand(void)
- Compute pseudo random number
- The return number in the range 0 to RAND_MAX
- Values produced by rand() can be scaled and
shifted to produce values in a specific range - General equation for scaling and shifting a
random number is n a rand() b - where a is a shifting value and b is the scaling
factor
33Random Number Generator Functions (continue)
- include ltstdlib.hgt
- void srand(unsigned int x)
- The srand() takes an unsigned integer argument
and seeds function rand() to produce a different
sequence of random numbers for each execution of
the problem - To reinitialize the generator, use 1 as the seed
argument - To randomize without the need for entering a seed
each time, use srand(time(NULL)) - where function time returns the number of
seconds, the time function is in lttime.hgt
34Example 10 4 Using Random Number Generation
Function
- / fig05_07.c - Shifted, scaled integers
produced by 1 rand() 6 / - include ltstdio.hgt
- include ltstdlib.hgt
- / function main begins program execution /
- int main()
-
- int i / counter /
-
- / loop 20 times /
- for ( i 1 i lt 20 i )
- / pick random number from 1 to 6 and
output it / - printf( "10d", 1 ( rand() 6 ) )
35Example 10 4 Using Random Number Generation
Function
- / if counter is divisible by 5, begin new
line of output / - if ( i 5 0 )
-
- printf( "\n" )
- / end if /
- / end for /
- return 0 / indicates successful termination
/ - / end main /
36Example 10-4 Using Random Number Generation
Function Output
37Example 10 5 A Program for Rolling Two Dices
- This program rolls two dices using rand()
function, computes sum, and determines the
winning outcomes - 7 or 11 WON
- 2, 3, or 12 LOST
- Other numbers 1, 4, 5, 6, 8, 9, 10 CONTINUE to
roll again - This program has the following characteristics
- Use a homemade function rollDice() which contains
srand(), rand(), and time() for rolling two
dices, and return the sum of the two dices - Use enum Status(WON, LOST, CONTINUE) to define a
new data type which is a sub-integer type WON
0, LOST 1, and CONTINUE 2, which enhances
the readability - Use multiple decision making structures switch,
case,
38Example 10 5 A Program for Rolling Two Dices
(cont.)
- include ltstdio.hgt
- include ltstdlib.hgt
- include lttime.hgt /contains prototype for
function time/ - / enumeration constants represent game status /
- enum Status CONTINUE, WON, LOST
- int rollDice( void ) / function prototype /
- / function main begins program execution /
- int main()
-
- int sum / sum of rolled dice /
- int myPoint / point earned /
39Example 10 5 A Program for Rolling Two Dices
(cont.)
- / can contain CONTINUE, WON, or LOST /
- enum Status gameStatus
- /randomize random number generator using
current time/ - srand( time( NULL ) )
- sum rollDice() / first roll of the dice
/ - / determine game status based on sum of dice
/ - switch( sum )
- / win on first roll /
- case 7
- case 11 gameStatus WON break
- / lose on first roll /
- case 2
- case 3
- case 12 gameStatus LOST break
40Example 10 5 A Program for Rolling Two Dices
(cont.)
- / remember point /
- default gameStatus CONTINUE
- myPoint sum
- printf( "Point is d\n",
myPoint ) - break / optional /
- / end switch /
- / while game not complete /
- while ( gameStatus CONTINUE )
-
- sum rollDice() / roll dice again /
- / determine game status /
- if ( sum myPoint ) / win by
making point / - gameStatus WON / game over,
player won / - else
41Example 10 5 A Program for Rolling Two Dices
(cont.)
- if ( sum 7 ) / lose
by rolling 7 / - gameStatus LOST / game
over, player lost / - / end else /
- / end while /
- / display won or lost message /
- if ( gameStatus WON )
- printf( "Player wins\n" ) / did
player win? / - else
- printf( "Player loses\n" ) / player
lost / - return 0 / indicates successful termination
/ - / end main /
42Example 10 5 A Program for Rolling Two Dices
(cont.)
- / roll dice, calculate sum and display results
/ - int rollDice( void )
-
- int dice1 / first die /
- int dice2 / second die /
- int workSum / sum of dice /
- dice1 1 ( rand() 6 ) / pick
random die1 value / - dice2 1 ( rand() 6 ) / pick
random die2 value / - workSum dice1 dice2 / sum die1 and
die2 / - / display results of this roll /
- printf( "Player rolled d d d\n",
dice1, dice2, workSum ) - return workSum / return sum of dice /
- / end function rollRice /
43Example 10 5 A Program for Rolling Two Dices
(cont.)
44Summary
- Standard Math.h Library
- Standard Utility Library ltstdlib.hgt
- Examples using Standard math and Utility library
- Next
- Storage classes and Scope rules
- Recursive Functions
- Standard Input/Output ltstdio.hgt
- Standard limits ltlimits.hgt
- Standard floating-point ltfloat.hgt
45Question?