double name_of_your_function( double name_of_your_input) { // ... local variables, computations ... return the_answer; }
#define PI (4*atan(1))
Example: convert miles to kilometers
Write a function to convert degrees Fahrenheit to degrees Celsius.
Degrees Celsius is degrees Fahrenheit, minus 32, times 5/9.
Write a function to compute the surface area of a sphere of radius r.
The area is 4πr2.
Write a function to compute the probability of a collision (i.e. duplicate value) when 5 values are selected randomly from a set of n possibilities. The probability of at least one collision is 1 minus the probability of no collisions:
Test using n=365.
Write a function to evaluate the following rational polynomial (from page 39) using nested form to minimize the number of multiplications:
Nested form for polynomial evaluation (Horner's Rule), to minimize number of multiplications:
Math: p = a x3 + b x2 + c x + d C: p = a*x*x*x + b*x*x + c*x + d; p = (a*x*x + b*x + c)*x + d; // factor out one x p = ((a*x + b)*x + c)*x + d; // factor out another x -> nested formnth degree poly, n multiplications
If we try to evaluate the expression in one statement, it becomes too long to be easily read:
f = (x*x*x - 2*x*x + x - 6.3)/(x*x + 0.05005*x - 3.14);We could break the statement into two lines:
f = (x*x*x - 2*x*x + x - 6.3)/ (x*x + 0.05005*x - 3.14);Another solution is to compute the numerator and denominator separately:
numerator = x*x*x - 2*x*x + x - 6.3; denominator = x*x + 0.05005*x - 3.14; f = numerator/denominator;The variables x, numerator, denominator, and f must be floating-point variables (i.e. double) in order to compute the correct value of f.