20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

132 Chapter 8 Work<strong>in</strong>g with Functions<br />

It is necessary to test the absolute difference of guess 2 and x aga<strong>in</strong>st ε <strong>in</strong> step 2 because<br />

the value of guess can approach the square root of x from either side.<br />

Now that you have an algorithm for f<strong>in</strong>d<strong>in</strong>g the square root at your disposal, it once<br />

aga<strong>in</strong> becomes a relatively straightforward task to develop a function to calculate the<br />

square root. For the value of ε <strong>in</strong> the follow<strong>in</strong>g function, the value .00001 was arbitrarily<br />

chosen. See the example <strong>in</strong> Program 8.8.<br />

Program 8.8 Calculat<strong>in</strong>g the Square Root of a Number<br />

// Function to calculate the absolute value of a number<br />

#<strong>in</strong>clude <br />

float absoluteValue (float x)<br />

{<br />

if ( x < 0 )<br />

x = -x;<br />

return (x);<br />

}<br />

// Function to compute the square root of a number<br />

float squareRoot (float x)<br />

{<br />

const float epsilon = .00001;<br />

float guess = 1.0;<br />

while ( absoluteValue (guess * guess - x) >= epsilon )<br />

guess = ( x / guess + guess ) / 2.0;<br />

}<br />

return guess;<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

pr<strong>in</strong>tf ("squareRoot (2.0) = %f\n", squareRoot (2.0));<br />

pr<strong>in</strong>tf ("squareRoot (144.0) = %f\n", squareRoot (144.0));<br />

pr<strong>in</strong>tf ("squareRoot (17.5) = %f\n", squareRoot (17.5));<br />

}<br />

return 0;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!