ECET 264 C Programming Language with Applications Lecture 17 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin http://www.etcs.ipfw.edu/~lin March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 1 Lecture 17- C Standard Library Functions C Standard Library Standard Math library <math.h> • Standard Math Function Prototype • Examples Using math.h Example 1717-1: Using Trigonometry Functions: sin(), cos(), cos(), and tan() • • Ceiling and Floor Functions Trigonometry and Inverse Trigonometric Functions • Hyperbolic Functions • Logarithm Functions March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 2 1 Lecture 17 - C Standard Library Functions (continue) Power and Square Functions • Example 1717-2: Testing Math Functions • Example 1717-3: Testing More Math Functions and Program Documentation Standard Utility Library <sdtlib.h> • Random Number Generation Functions Examples Using stdlib.h • Example 1717-4: Using Random Number Generation Function • Example 1717-5: A Program for Rolling Two Dices Summary March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 3 The C Standard Library Standard C functions, types, and macros of the standard library are declared in standard header files. Headers files can be accessed by use # include <header> Headers must be included outside of any external declaration before the use of any C functions. The standard headers are: <assert.h >, <ctype.h >, <assert.h>, <ctype.h>, <errno.h>, >, <float.h float.h>, >, <limit.h limit.h>, >, <local.h local.h>, >, <math.h>, errno.h < < < <setjmp.h>, >, <stdarg.h >, <stddef.h >, setjmp.h>, <signal.h <signal.h>, <stdarg.h>, <stddef.h>, <stdio.h>, >, <string.h >, and <time.h > stdio.h>, <stdlib.h <stdlib.h>, <string.h>, <time.h> Dscuss only <stdio.h >, <math.h >, <stdlib.h >, <stdio.h>, <math.h>, <stdlib.h>, <.limit.h >, and <float.h > <.limit.h>, <float.h> March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 4 2 Standard Math Function Prototype <math.h> - the header file of mathematical functions that declare mathematical functions and macros The C standard mathematics functions, <math.h>, must be included in the C program when using math functions All functions in <math.h> allow the programmer to perform certain common mathematical calculations. March 21, 2009 5 Lecture 17&18 - Prof. Paul I. Lin Standard Math Function Prototype (cont.) All the input arguments and return value from a math function are defined as double floatingfloatingpoint 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 Return value type Argument type double sin(double x); Function name March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin Parameter name 6 3 Standard Math Functions Prototype (cont.) Standard math functions available for use through header file inclusion #include <math.h > are: <math.h> sin(x) sine of x cos(x) ) cosine of x cos(x tan(x) tangent of x pow(x, pow(x, y) x goes to power of y, x^y sqrt(x) square root of x sqrt(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. March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 7 Example 17-1: Using Trigonometry Functions: sin(), cos(), and tan() Problem Statement: Write a simple C program to explain how to use trigonometry functions sin(), cos(), cos(), and tan() functions. Analysis and Requirements: Two symbolic constants are defined using the identity: 360° 360° = 2π 2π radians define variable as double floatingfloating-point number type examine the program output by print them using the %1f format specifier for double type. March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 8 4 Example 17-1: Using Trigonometry Functions: sin(), cos(), and tan() (cont.) /* trigomath.c */ #include <math.h> #include <stdio.h > <stdio.h> #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, ysin, ycos, ycos, ytan; ytan; ysin = sin(theta * Deg_to_Rad); 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) Deg_to_Rad) = sin(0.7853975); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 9 Example 17-1: Using Trigonometry Functions: sin(), cos(), and tan() (cont.) ycos = cos(theta * Deg_to_Rad); Deg_to_Rad); ytan = tan(theta * Deg_to_Rad); Deg_to_Rad); printf("sin(%lf Degree) = %lf\ %lf\n", theta, ysin); ysin); printf("cos(%lf Degree) = %lf\ %lf\n", theta, ycos); ycos); printf("tan(%lf Degree) = %lf\ %lf\n", theta, ytan); ytan); printf("tan(%lf Degree) = %e\ %e\n", theta, ytan); ytan); } March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 10 5 Example 17-1 (cont.) 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.999987e9.999987e-001 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 11 Ceiling 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(xceil(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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 12 6 Trigonometric 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 13 Trigonometric and Inverse Trigonometric Functions (cont.) 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() 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 π March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 14 7 Hyperbolic 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 15 Logarithm 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 16 8 Power 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 17 Example 17-2: Testing Math Function /* logex.c - Write a program to test various math functions*/ functions*/ #include <math.h> #include <stdio.h > <stdio.h> #define PI 3.14159 void main(void) { double y; printf("log10(1000.0) = %lf\ %lf\n", log10(1000.0)); printf("log(1000.0) = %lf\ %lf\n", log(1000.0)); printf("exp(1) = %lf\ %lf\n", exp(1)); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 18 9 Example 17-2: Testing Math Function (cont.) (cont.) printf("pow(2,16) = %8.0lf\ %8.0lf\n", pow(2.0, 16.0)); printf("sqrt(9) = %lf\ %lf\n", sqrt(9.0)); printf("ceil(99.9999) = %lf\ %lf\n", ceil(99.9999)); printf("ceil(99.4) = %lf\ %lf\n", ceil(99.4)); printf("ceil(99.0001) = %lf\ %lf\n", ceil(99.0001)); printf("floor(99.9999)= %lf\ %lf\n", floor(99.9999)); printf("floor(99.4) = %lf\ %lf\n", floor(99.4)); printf("floor(99.0001) = %lf\ %lf\n", floor(99.0001)); } March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 19 Example 17-2: Testing Math Function (cont.) (cont.) Output: Output: log10(1000.0) log(1000.0) exp(1) pow(2,16) sqrt(9) ceil(99.9999) ceil(99.4) ceil(99.0001) floor(99.9999) floor(99.4) floor(99.0001) March 21, 2009 = = = = = = = = = = = 3.000000 6.907755 2.718282 65536 3.000000 100.000000 100.000000 100.000000 99.000000 99.000000 99.000000 Lecture 17&18 - Prof. Paul I. Lin 20 10 Example 17 – 3: Testing More Math Functions and Program Documentation Problem Statement March 21, 2009 As a technical staff, you are asked to test the following math functions and report your finding to other technical staffs in your group. The functions that will be tested are sqrt(), sqrt(), exp(), log(), log10(), fabs(), fabs(), ceil(), floor(), pow(), pow(), fmod(), fmod(), sin(), cos(), cos(), and tan() Lecture 17&18 - Prof. Paul I. Lin 21 Example 17 – 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: 1. What is the testing environment? Microsoft Visual Studio.NET running under Windows Vista, Windows XP, Windows 2003, Windows 2000, Linux, etc March 21, 2009 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(), sqrt(), exp(), log(), log10(), fabs(), fabs(), ceil(), floor(), pow(), pow(), fmod(), fmod(), sin(), cos(), cos(), and tan() Lecture 17&18 - Prof. Paul I. Lin 22 11 Example 17 – 3: Testing More Math Functions and Program Documentation (cont.) /* ex05_03.c */ /* Testing the math library functions */ #include <stdio.h > <stdio.h> #include <math.h > <math.h> /* function main begins program execution */ int main() { /* calculates and outputs the square root */ printf( printf( "sqrt(%.1f) = %.1f\ %.1f\n", 900.0, sqrt( sqrt( 900.0 ) ); printf( printf( "sqrt(%.1f) = %.1f\ %.1f\n", 9.0, sqrt( sqrt( 9.0 ) ); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 23 Example 17 – 3: Testing More Math Functions and Program Documentation (cont.) /* calculates and outputs the exponential function e to the x */ printf( printf( "exp(%.1f) = %f %f\n", 1.0, exp( 1.0 ) ); printf( ( "exp(%.1f) = %f printf %f\n", 2.0, exp( 2.0 ) ); /* calculates and outputs the logarithm (base e) */ printf( printf( "log(%f "log(%f)) = %.1f\ %.1f\n", 2.718282, log( 2.718282 ) ); printf( printf( "log(%f "log(%f)) = %.1f\ %.1f\n", 7.389056, log( 7.389056 ) ); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 24 12 Example 17 – 3: Testing More Math Functions and Program Documentation (cont.) /* calculates and outputs the logarithm (base 10) */ printf( printf( "log10(%.1f) = %.1f\ %.1f\n", 1.0, log10( 1.0 ) ); printf( printf( "log10(%.1f) = %.1f\ %.1f\n", 10.0, log10( 10.0 ) ); printf( printf( "log10(%.1f) = %.1f\ %.1f\n", 100.0, log10( 100.0 ) ); /* calculates and outputs the absolute value */ printf( printf( "fabs(%.1f) = %.1f\ %.1f\n", 13.5, fabs( fabs( 13.5 ) ); printf( printf( "fabs(%.1f) = %.1f\ %.1f\n", 0.0, fabs( fabs( 0.0 ) ); printf( printf( "fabs(%.1f) = %.1f\ %.1f\n", -13.5, fabs( fabs( -13.5 ) ); /* calculates and outputs ceil( x ) */ printf( printf( "ceil(%.1f) = %.1f\ %.1f\n", 9.2, ceil( 9.2 ) ); printf( printf( "ceil(%.1f) = %.1f\ %.1f\n", -9.8, ceil( -9.8 ) ); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 25 Example 17 – 3: Testing More Math Functions and Program Documentation (cont.) /* calculates and outputs floor( x ) */ printf( printf( "floor(%.1f) = %.1f\ %.1f\n", 9.2, floor( 9.2 ) ); printf( printf( "floor(%.1f) = %.1f\ %.1f\n", -9.8, floor( -9.8 ) ); /* calculates and outputs pow( pow( x, y ) */ printf( printf( "pow(%.1f, %.1f) = %.1f\ %.1f\n", 2.0, 7.0, pow( pow( 2.0, 7.0 ) ); printf( printf( "pow(%.1f, %.1f) = %.1f\ %.1f\n", 9.0, 0.5, pow( pow( 9.0, 0.5 ) ); /* calculates and outputs fmod( fmod( x, y ) */ printf( printf( "fmod(%.3f/%.3f) = %.3f\ %.3f\n", 13.675, 2.333, fmod( fmod( 13.675, 2.333 ) ); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 26 13 Example 17 – 3: Testing More Math Functions and Program Documentation (cont.) /* calculates and outputs sin( x ) */ printf( printf( "sin(%.1f) = %.1f\ %.1f\n", 0.0, sin( 0.0 ) ); /* calculates and outputs cos( cos( x ) */ printf( printf( "cos(%.1f) = %.1f\ %.1f\n", 0.0, cos( cos( 0.0 ) ); /* calculates and outputs tan( x ) */ printf( printf( "tan(%.1f) = %.1f\ %.1f\n", 0.0, tan( 0.0 ) ); return 0; /* indicates successful termination */ } /* end main */ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 27 Example 17 – 3: Testing More Math Functions and Program Documentation March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 28 14 Example 17-3: Program Documentation /************************************************************************/ /************************************************************************/ /* Program Name: ex5*/ ex5-03.c /* Programmer: Paul Lin */ /* Date: March 20, 2009 */ /* Version: 1.0 */ /* Description: */ /* This program tests the following math functions sqrt(), sqrt(), exp(), */ /* log(), log10(), fabs(), fabs(), ceil(), floor(), pow(), pow(), fmod(), fmod(), sin(), cos(), 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 */ /************************************************************************/ /************************************************************************/ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 29 Utility Function Prototypes <stdlib.h> - the standard library header file which declares utility functions for number conversion, storage allocation, random number generation, absolute value, etc. Absolute Value Calculation <stdlib.h> • 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 30 15 Utility Function Prototypes (continue) ASCII strings to Numerical Value Conversion <stdlib.h> • double atof(const char *string); Convert ASCII string to floatfloat-point number • int atoi(const char *string); Convert ASCII string to integer number • long atol(const char *string); Convert ASCII string to long integer March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 31 Random Number Generator Functions Random Number Generator Functions - in <stdlib.h>, stdlib.h>, 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 twotwo-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. March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 32 16 Random Number Generator Functions (cont.) #include <stdlib.h > <stdlib.h> int rand(void) 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 March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin Random Number Generator Functions 33 (cont.) #include <stdlib.h > <stdlib.h> void srand(unsigned int x) • The srand() 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)) srand(time(NULL)) where function time returns the number of seconds, the time function is in <time.h > <time.h> March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 34 17 Example 17 – 4: Using Random Number Generation Function /* fig05_07.c - Shifted, scaled integers produced by 1 + rand() % 6 */ #include <stdio.h > <stdio.h> #include <stdlib.h > <stdlib.h> /* function main begins program execution */ int main() { int i; /* counter */ /* loop 20 times */ for ( i = 1; i <= 20; i++ ) { /* pick random number from 1 to 6 and output it */ printf( printf( "%10d", 1 + ( rand() % 6 ) ); March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 35 Example 17 – 4: Using Random Number Generation Function /* if counter is divisible by 5, begin new line of output */ if ( i % 5 == 0 ) { printf( printf( "\ "\n" ); } /* end if */ } /* end for */ return 0; /* indicates successful termination */ } /* end main */ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 36 18 Example 17-4: Using Random Number Generation Function: Output March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 37 Example 17 – 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() rollDice() which contains srand(), srand(), rand(), and time() for rolling two dices, and return the sum of the two dices • Use enum Status(WON, Status(WON, LOST, CONTINUE) to define a new data type which is a subsub-integer type: WON ==0, LOST == 1, and CONTINUE == 2, which enhances the readability • Use multiple decision making structures: switch, case, March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 38 19 Example 17 – 5: A Program for Rolling Two Dices (cont.) #include <stdio.h > <stdio.h> #include <stdlib.h > <stdlib.h> #include <time.h > /*contains prototype for function time*/ <time.h> /* enumeration constants represent game status */ enum Status { CONTINUE, WON, LOST }; int rollDice( /* function prototype */ rollDice( void ); /* function main begins program execution */ int main() { int sum; /* sum of rolled dice */ int myPoint; myPoint; /* point earned */ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 39 Example 17 – 5: A Program for Rolling Two Dices (cont.) /* can contain CONTINUE, WON, or LOST */ enum Status gameStatus; gameStatus; /*randomize random number generator using current time*/ srand( srand( time( NULL ) ); sum = rollDice() 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; March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 40 20 Example 17 – 5: A Program for Rolling Two Dices (cont.) /* remember point */ default: gameStatus = CONTINUE; myPoint = sum; printf( printf( "Point is %d %d\n", myPoint ); break; /* optional */ } /* end switch */ /* while game not complete */ while ( gameStatus == CONTINUE ) { sum = rollDice(); rollDice(); /* roll dice again */ /* determine game status */ if ( sum == myPoint ) /* win by making point */ gameStatus = WON; /* game over, player won */ else { March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 41 Example 17 – 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( printf( "Player wins\ wins\n" ); /* did player win? */ else printf( printf( "Player loses\ loses\n" ); /* player lost */ return 0; /* indicates successful termination */ } /* end main */ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 42 21 Example 17– 5: A Program for Rolling Two Dices (cont.) /* roll dice, calculate sum and display results */ int rollDice( rollDice( void ) { int dice1; /* first die */ int dice2; /* second die */ int workSum; 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( printf( "Player rolled %d + %d = %d %d\n", dice1, dice2, workSum ); return workSum; workSum; /* return sum of dice */ } /* end function rollRice */ March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 43 Example 17– 5: A Program for Rolling Two Dices (cont.) March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 44 22 Summary March 21, 2009 Standard Math.h Library Standard Utility Library <stdlib.h> Examples using Standard math and Utility library Next • Storage classes and Scope rules • Recursive Functions • Standard Input/Output <stdio.h> • Standard limits <limits.h> • Standard floating-point <float.h> Lecture 17&18 - Prof. Paul I. Lin 45 Question Answer [email protected] March 21, 2009 Lecture 17&18 - Prof. Paul I. Lin 46 23
© Copyright 2024 Paperzz