For harder maths, C has a toolbox called math.h. Include it at the top:
| Function | What it does | Example | Result |
|---|---|---|---|
sqrt(x) | Square root | sqrt(25) | 5 |
pow(x, y) | x to the power of y | pow(2, 10) | 1024 |
fabs(x) | Remove the minus sign | fabs(-3.5) | 3.5 |
round(x) | Round to nearest whole | round(2.6) | 3 |
floor(x) | Round down | floor(2.9) | 2 |
ceil(x) | Round up | ceil(2.1) | 3 |
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f\n", sqrt(25.0));
printf("%.0f\n", pow(2, 10));
printf("%.1f\n", fabs(-3.5));
printf("%.0f %.0f %.0f\n", round(2.6), floor(2.9), ceil(2.1));
return 0;
}Output
5.0 1024 3.5 3 2 3
All of these give back a double, so print them with %f (or %.0f for no decimals).
Example: area of a circle
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main() {
double radius;
scanf("%lf", &radius);
printf("Area: %.2f\n", PI * pow(radius, 2));
return 0;
}Input (what the user types)
3
Output
Area: 28.27
Tip: On your own computer, add
-lmwhen you compile a program that usesmath.h:gcc circle.c -o circle -lm.
Remember:
#include <math.h>gives yousqrt,pow,fabs,round,floorandceil.