C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

20. Advanced Math (for the Computer, Not You!)


In This Chapter


  • Practicing your math

  • Doing more conversions

  • Getting into trig and other really hard stuff

  • Getting random


This chapter extends your knowledge of built-in functions to the numeric functions. C helps you do
math that the C operators can’t do alone. More than anything else, the C built-in numeric functions
supply routines that you don’t have to write yourself.


A lot of C’s built-in math functions are highly technical—not that their uses are difficult, but their
purposes might be. Unless you need trigonometric and advanced math functions, you might not find a
use for many of the functions described in this chapter.


Tip

Some people program in C for years and never need many of these functions. You
should read this chapter’s material to get an idea of what C can accomplish so you’ll
know what’s available if you ever do need these powerful functions.

Practicing Your Math


All the functions this chapter describes require the use of the math.h header file. Be sure to include
math.h along with stdio.h if you use a math function. The first few math functions are not so
much math functions as they are numeric functions. These functions convert numbers to and from other
numbers.


The floor() and ceil() functions are called the floor and ceiling functions, respectively. They
“push down” and “push up” nonintegers to their next-lower or next-higher integer values. For
example, if you wanted to compute how many dollar bills were in a certain amount of change (that
includes dollars and cents), you could use floor() on the amount. The following code does just
that:


Click here to view code image


change = amtPaid – cost; //These are all floating-point values
dollars = floor(change);
printf("The change includes %f dollar bills.\n", dollars);
Free download pdf