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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Console Input and Output: printf() and scanf() →← Variable Assignment and Typecasting in CNext lesson: Console Input and Output: printf() and scanf() →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between floor, ceil and round in C?
Why does sin(30) not return 0.5 in C?
What does nan mean in C output?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →