Using the math.h Library, Explained with Code Examples

UPI Study › Courses › Programming in C › Free lessons › Lesson 3.4 Free with a free account

Using the math.h Library

Programming in C · Chapter 3: Data Types, Variables, Math Library, and Console I/OSection 3.4 · lesson 16 of 786 min · free with a free account

← Variable Assignment and Typecasting in CNext lesson: Console Input and Output: printf() and scanf() →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Use math.h functions for powers, roots, rounding and trigonometry.

  • Include math.h and link the math library with -lm
  • Use pow, sqrt, fabs, ceil, floor and round correctly
  • Convert degrees to radians before calling sin and cos
  • Recognize NaN results and test for them with isnan

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (767 words). Read along, or search it.

Opening Problem

Distance Across the Arcade Floor

The Starlight Arcade floor is a grid. Space Dash stands at position one, two, and Pixel Pinball at four, six. How many steps apart are they, in a straight line? You need a square root, and C's plus, minus, times and divide can't take one. The math library can. Using it takes two steps, and forgetting either one fails in a different way.

Two Steps

Include the Header, Link the Library

Step one: hash include math dot h pastes in a header. It's a list that tells the compiler: a function called square root exists, and takes a double. Like reading a restaurant's menu. Step two: the linker attaches the real code. On Linux with GCC, the math code lives in its own library. You ask for it with dash l m: link the math library. Forget dash l m there, and the linker complains: undefined reference to pow. On a Mac, the math code is part of the system library, so it links either way. We type dash l m anyway, in every math program, so the same command works on both.

Missing Header

Calling sqrt Without a Declaration

Now forget step one instead. This program calls square root with no math header. Clang stops: call to undeclared library function sqrt. Since C99, a function must be declared before it's called. And the note names the cure: include the header math dot h. Add the include line, build again, and it prints 12.0.

Function Tour

Powers, Roots and Rounding

Here's the toolbox. Pow raises to a power: two to the tenth is 1024. Square root of 144 is 12. And f abs removes the minus sign. Every one of them takes doubles and returns a double, even when the answer is whole. That's why each prints with a point zero. For ints, abs lives in another header, standard lib dot h. The three rounding functions are the tricky ones. Ceil goes to the next whole number up, floor to the next one down, and round to the nearest, sending halves away from zero. Negative numbers show the difference. Ceil of minus 2.5 is minus two. Floor is minus three. And round is minus three too. So floor doesn't simply delete the decimals. To cut toward zero, use an int cast, as in lesson 3.3.

Quick Check

Floor, Ceil and Round of Minus 1.5

Quick check. x is minus 1.5. The program prints floor, ceil and round of x, with no decimals. What are the three numbers? Pause and predict. It prints minus two, minus one, minus two. Floor goes down, toward the smaller number: minus two. Ceil goes up: minus one. And round sends the half away from zero, so minus 1.5 rounds to minus two. Cutting the decimals off would give minus one for all three.

Worked Example

Distance and a Ticket Rule

Back to the arcade floor. The straight-line distance comes from Pythagoras: the square root of the two squared differences, added together. Three steps across and four steps down give five steps. Run it: 5.00. The second half is a ticket rule: one ticket per hundred points, and a part-way bunch still earns a whole ticket. A score of 1250 is 12.5 hundreds, and ceil lifts that to 13. Writing 100.0 matters. With plain 100, the division would already be a whole 12 before ceil ever saw it.

Trigonometry

Converting Degrees to Radians

Sine and cosine expect an angle in radians, not degrees. A half turn is 180 degrees, which is pi radians, about 3.14159. To convert, multiply the degrees by pi and divide by 180. M underscore PI isn't part of standard C, though some systems add it, so the program defines its own pi. Converted, the sine of 30 degrees is 0.5, and so is the cosine of 60 degrees. Without the conversion, sine of thirty treats it as thirty radians, and gives minus 0.9880. A perfectly legal, wrong answer, with no error. You only catch it by checking the numbers.

Special Value

The Square Root of Minus One

One more case. No ordinary number multiplied by itself gives minus one. So what does the square root of minus one return? A special value, NaN, short for not a number. Printed, it shows as nan. And the function isnan answers whether a value is one.

Story Ending

The Walking-Time Screen

Priya once built a walking-time screen for the arcade, and the numbers looked wrong, though nothing failed to build. Sine wants radians, Sam said. She multiplied by pi over 180, and the screen matched.

Key Takeaways

Header, Link Flag and Doubles

To recap. Include math dot h so the compiler knows the functions, and link with dash l m so the linker finds them. They take and return doubles. Ceil goes up, floor goes down, and round sends halves away from zero. Sine and cosine want radians, and an impossible result such as the square root of minus one comes back as NaN.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Using the math.h Library

Why does a C program need -lm when using math.h?
The -lm option links the math library, which on Linux with GCC holds the code for functions such as pow and sqrt. Including math.h only declares the functions so the compiler knows they exist; the linker still needs the actual code. Without -lm on such systems, linking can fail with undefined reference to pow. On a Mac the math code is in the system library, and adding -lm is harmless.
What is the difference between floor, ceil and round in C?
floor goes down to the next whole number, ceil goes up, and round goes to the nearest, sending halves away from zero. For 2.5 they give 2, 3 and 3. Negative numbers show the difference: for -2.5, floor gives -3, ceil gives -2, and round gives -3. All three return a double, and to cut toward zero instead, use an int cast.
Why does sin(30) not return 0.5 in C?
sin(30) does not return 0.5 because C's sin and cos expect radians, not degrees, and 30 radians gives about -0.988. To convert, multiply degrees by pi and divide by 180, so sin(30 * PI / 180) gives 0.5 to printed precision when PI is defined. Standard C does not define M_PI, although some systems add it, so portable programs often define their own pi constant.
What does nan mean in C output?
nan stands for not a number, a special floating-point value returned when a calculation has no real answer, such as sqrt(-1). No real number multiplied by itself gives a negative number, so sqrt cannot return an ordinary value. printf typically shows it as nan, or -nan on some systems, and the isnan macro from math.h tests whether a value is NaN.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →