Transcript lecture10x

What are functions?
1.
A piece of code that performs an operation that
can be used by the main program or by other
functions
2. A sophisticated if –else statement that always
goes into the else part and never into the if part
3. Just some stuff the compiler uses and the user
never has to use or see
4. An out of this world thrill ride at the Walt Disney
World Resort in Orlando, FL!!!
Using Functions
Avoid re-inventing the wheel
Using existing functions as building-blocks to create
new programs
“Prepackaged” functions in the C Standard Library
can be used.
User-defined functions can also be used (talk about
this next lecture).
Example: Suppose you want to find
cos(90°).
• 90° = π/2
• One way would be to calculate the power series:
2
4
6
8
x
x
x
x
cos( x)  1      
2! 4! 6! 8!
• Or, you can just use include the math.h header which
contains a built in cosine function.
Commonly Used Math Library Functions
Function
Description
Example
sqrt( x )
square root of x
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
exp( x )
exponential function ex
exp( 1.0 ) is 2.718282
exp( 2.0 ) is 7.389056
log( x )
natural logarithm of x (base e)
log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x )
logarithm of x (base 10)
log10( 1.0 ) is 0.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( x )
absolute value of x
fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( x )
rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x
ceil( -9.8 ) is -9.0
Commonly Used Math Library Functions
Function
Description
Example
floor( x )
rounds x to the largest integer
not greater than x
floor( 9.2 ) is 9.0
x raised to power y (xy)
pow( 2, 7 ) is 128.0
pow( x, y )
floor( -9.8 ) is -10.0
pow( 9, .5 ) is 3.0
fmod( x, y )
remainder of x/y as a floatingpoint number
fmod( 13.657, 2.333 ) is 1.992
sin( x )
trigonometric sine of x
(x in radians)
sin( 0.0 ) is 0.0
cos( x )
trigonometric cosine of x
(x in radians)
cos( 0.0 ) is 1.0
tan( x )
trigonometric tangent of x
(x in radians)
tan( 0.0 ) is 0.0
For your in class assignment
Use #include math.h
Take a look at /usr/include/math.h and note the
#define
• Use M_PI for pi or define your own pi.
• Use the function acos(argument) to find the inverse
cosine
• In order to compile using the math library, you must use
a compiler flag –lm:
• gcc program.c –lm –o executable
Or
gcc program.c –o executable –lm (this way is better)
Law of Cosines
Leg 2
a 2  b2 - c 2
cos( ) 
2ab
a 2  c 2  b2
cos(  ) 
2ac
b2  c 2  a 2
cos( ) 
2bc
Hypotenuse
 a 2  b2  c 2 
  arccos 

2
ab


 a 2  c 2  b2 
  arccos 

2
ac


 b2  c 2  a 2 
  arccos 

2
bc


deg ree 
180


  3.14159265
Leg 1