math.h
- C course
- Intermediate
- Lesson 84/116
- 5 min
Learn math functions in math.h.
math.h
The <math.h> header provides mathematical functions: square root (sqrt), power (pow), floor rounding (floor), ceiling rounding (ceil) and trigonometry (sin, cos).
These functions work on double. sqrt(25.0) returns 5.0. pow(2.0, 3.0) returns 8.0 (2 to the power 3). floor(3.7) gives 3.0, ceil(3.2) gives 4.0. When integer-like operations produce fractional results, floor and ceil help. You may need to link with -lm depending on the system; modern systems often don't require it. Square root of a negative number returns NaN; checking the input is a good habit.
The sqrt and pow example
Let's combine two core math operations: square root and power. Both return double; we print the output with %.2f to show two decimal places.
Definition: double r = sqrt(25.0); double p = pow(2.0, 3.0); printf("%.2f %.2f\n", r, p);. Here sqrt(25.0) gives 5.0, pow(2.0, 3.0) gives 8.0. Output: 5.00 8.00. The %.2f specifier shows two digits after the decimal; this is suitable for money or measurement values. If you want an integer, cast with (int)r; but this truncates, it doesn't round. To round, use floor or ceil.
Practice sqrt and pow
In main do double r = sqrt(25.0); and double p = pow(2.0, 3.0);. Print with printf("%.2f %.2f\n", r, p);.
Starter code
#include <stdio.h>
#include <math.h>
// main: find square root of 25 with sqrt
// compute 2 to the power 3 with pow
// print both with printf
int main(void) {
// write here
return 0;
}Sample solution
#include <stdio.h>
#include <math.h>
int main(void) {
double r = sqrt(25.0);
double p = pow(2.0, 3.0);
printf("%.2f %.2f\n", r, p);
return 0;
}Expected output
5.00 8.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Power
double p = pow(2.0, ____);
double p = pow(2.0, 3.0);
Explanation: pow(2.0, 3.0) gives 2 to the power 3 = 8.0.
2 What does floor(3.7) return?
- 4.0
- 3.7
- 3.0 Correct answer
- 3
Explanation: floor rounds 3.7 down to 3.0.
3 math functions
| Term | Meaning |
|---|---|
sqrt |
square root |
pow |
power |
floor |
round down |
ceil |
round up |