The math.h header in C provides a powerful collection of functions to handle mathematical computations. From basic arithmetic to complex trigonometric, exponential, and logarithmic operations — math.h helps you avoid writing long custom logic for common mathematical tasks.
🔧 How to Use math.h
#include <math.h>⚠️ Important: When compiling, link with the math library by adding -lm at the end of your gcc command:
gcc program.c -lmWhy? Because math.h functions are part of the libm library (math library), and -lm tells the compiler to link against it.
📚 Categorized Overview of Key math.h Functions
✅ Power and Roots
Function | Description | Example | Output |
|---|---|---|---|
| Returns √x (square root) |
|
|
| Returns xʸ (x raised to y) |
|
|
| Returns cube root of x |
|
|
🔍 Examples:
#include <stdio.h>
#include <math.h>
int main() {
printf("Square root: %.2f\\n", sqrt(64)); // 8.00
printf("Power: %.2f\\n", pow(3, 4)); // 81.00
return 0;
}➕ Rounding Functions
Function | Description | Example | Output |
|---|---|---|---|
| Rounds down to nearest integer |
|
|
| Rounds up to nearest integer |
|
|
| Rounds to nearest integer |
|
|
| Truncates decimal (toward zero) |
|
|
🔹 Difference between floor, trunc, and round:
floor(-4.3)→5.0trunc(-4.3)→4.0round(-4.3)→4.0
➖ Absolute Value
Function | Description | Example |
|---|---|---|
| Absolute value of int |
|
| Absolute value of float/double |
|
📏 Logarithmic & Exponential Functions
Function | Description | Example | Output |
|---|---|---|---|
| Natural log (ln x) |
| ≈ |
| Log base 10 |
|
|
| Returns eˣ |
|
|
🔍 Use Case:
printf("log(100): %.2f\\n", log10(100)); // 2.00
printf("exp(1): %.2f\\n", exp(1)); // 2.72📐 Trigonometric Functions
Trigonometric functions use radians, not degrees.
Convert degrees to radians:
radians = degrees * (M_PI / 180.0)Function | Description | Example |
|---|---|---|
| Sine of angle x in radians |
|
| Cosine of x |
|
| Tangent of x |
|
Inverse Trigonometric:
Function | Description |
|---|---|
| Arc sine |
| Arc cosine |
| Arc tangent |
double angle = M_PI / 3;
printf("cos(60 deg): %.2f\\n", cos(angle)); // 0.5🧩 Other Helpful Functions
Function | Description | Example |
|---|---|---|
| Remainder of |
|
| Returns √(x² + y²) |
|
| Returns max |
|
| Returns min |
|
| IEEE remainder |
|
📂 Constant Macros in math.h
Macro | Value |
|---|---|
| 3.14159265358979323846 |
| 2.71828182845904523536 |
💡 These are not guaranteed in every compiler. If not found, define them yourself.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif<div class="infographic-cmath">
<style>
.infographic-cmath {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--code-bg: #1e1e2e;
--code-text: #d4d4e0;
--syn-keyword: #c586c0;
--syn-func: #dcdcaa;
--syn-comment: #6a9955;
}
.infographic-cmath[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--code-bg: #0d0d14;
--code-text: #d4d4e0;
}
.infographic-cmath {
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
background: var(--paper);
color: var(--ink);
font-family: 'Inter', -apple-system, sans-serif;
padding: 0 clamp(1rem, 4vw, 2.25rem) 1.25rem;
}
.infographic-cmath *, .infographic-cmath *::before, .infographic-cmath *::after {
box-sizing: border-box;
}
.infographic-cmath h1 {
font-family: 'Fraunces', Georgia, serif;
font-weight: 600;
font-size: clamp(1.3rem, 3.5vw, 1.65rem);
margin: 1.25rem 0 0.2rem;
text-align: center;
}
.infographic-cmath .subhead { color: var(--ink-soft); font-size: 0.85rem; margin-bottom: 1.1rem; text-align: center; }
.infographic-cmath .chip-row { display: flex; justify-content: center; gap: 0.35rem; margin-bottom: 0.8rem; flex-wrap: wrap; }
.infographic-cmath .chip {
all: unset;
cursor: pointer;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.76rem;
font-weight: 600;
padding: 0.36rem 0.7rem;
border-radius: 20px;
border: 1px solid var(--line);
color: var(--ink-soft);
transition: background 0.2s, color 0.2s, border-color 0.2s;
}
.infographic-cmath .chip:hover { border-color: var(--accent); }
.infographic-cmath .chip.is-active { background: var(--accent); border-color: var(--accent); color: #fff; }
.infographic-cmath .chip.small { font-size: 0.72rem; padding: 0.3rem 0.6rem; }
.infographic-cmath .code-panel {
background: var(--code-bg);
color: var(--code-text);
border-radius: 8px;
padding: 0.6rem 0.9rem;
font-family: 'IBM Plex Mono', monospace;
font-size: 0.85rem;
text-align: center;
margin-bottom: 0.9rem;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.infographic-cmath .syn-func { color: var(--syn-func); }
.infographic-cmath .field-row { display: flex; align-items: center; justify-content: center; gap: 0.6rem; margin-bottom: 0.8rem; flex-wrap: wrap; }
.infographic-cmath .field-row label { font-family: 'IBM Plex Mono', monospace; font-size: 0.82rem; color: var(--ink-soft); }
.infographic-cmath .field-row input {
font-family: 'IBM Plex Mono', monospace;
font-size: 0.9rem;
padding: 0.35rem 0.55rem;
border-radius: 6px;
border: 1px solid var(--line);
background: var(--paper);
color: var(--ink);
width: 6rem;
}
.infographic-cmath .result-panel {
text-align: center;
padding: 0.8rem 1rem;
background: var(--paper-alt);
border-radius: 8px;
font-family: 'IBM Plex Mono', monospace;
font-size: 1rem;
font-weight: 700;
color: var(--accent);
margin-bottom: 0.5rem;
}
.infographic-cmath .const-row { display: flex; justify-content: center; gap: 1rem; flex-wrap: wrap; margin-bottom: 0.5rem; }
.infographic-cmath .const-card {
text-align: center;
padding: 0.6rem 1rem;
background: var(--paper-alt);
border-radius: 8px;
font-family: 'IBM Plex Mono', monospace;
}
.infographic-cmath .const-card .cname { font-size: 0.8rem; color: var(--ink-soft); }
.infographic-cmath .const-card .cval { font-size: 0.95rem; font-weight: 700; color: var(--accent); }
.infographic-cmath .takeaway {
font-size: 0.82rem; color: var(--ink-soft);
margin-top: 1.3rem; border-top: 1px solid var(--line); padding-top: 0.9rem;
}
.infographic-cmath .takeaway strong { color: var(--ink); }
</style>
<h1>🧮 math.h Playground</h1>
<p class="subhead">gcc program.c -lm — pick a function, type numbers, get the real answer.</p>
<div class="chip-row" id="cat-tabs">
<button class="chip is-active" data-cat="power">Power/Roots</button>
<button class="chip" data-cat="round">Rounding</button>
<button class="chip" data-cat="abs">Absolute</button>
<button class="chip" data-cat="log">Log/Exp</button>
<button class="chip" data-cat="trig">Trig</button>
<button class="chip" data-cat="other">Other</button>
<button class="chip" data-cat="const">Constants</button>
</div>
<div class="chip-row small" id="fn-tabs"></div>
<div id="fn-area">
<div class="code-panel" id="fn-code"></div>
<div class="field-row" id="fn-fields"></div>
<div class="result-panel" id="fn-result"></div>
</div>
<div id="const-area" style="display:none;">
<div class="const-row">
<div class="const-card"><div class="cname">M_PI</div><div class="cval" id="const-pi"></div></div>
<div class="const-card"><div class="cname">M_E</div><div class="cval" id="const-e"></div></div>
</div>
</div>
<p class="takeaway"><strong>Every trig function here uses radians</strong> — that's why sin(90) looks wrong until you flip the unit toggle to degrees.</p>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-cmath')
|| document.querySelector('.infographic-cmath');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
function $(sel) { return wrapper.querySelector(sel); }
function cRound(x) { return x >= 0 ? Math.floor(x + 0.5) : Math.ceil(x - 0.5); }
function cFmod(x, y) { return y === 0 ? NaN : x - y * Math.trunc(x / y); }
function cRemainder(x, y) {
if (y === 0) return NaN;
const q = x / y;
let n = Math.round(q);
if (Math.abs(q - Math.trunc(q)) === 0.5) n = 2 * Math.round(q / 2);
return x - n * y;
}
const CATS = {
power: { label: 'Power/Roots', fns: ['sqrt', 'pow', 'cbrt'] },
round: { label: 'Rounding', fns: ['floor', 'ceil', 'round', 'trunc'] },
abs: { label: 'Absolute', fns: ['abs', 'fabs'] },
log: { label: 'Log/Exp', fns: ['log', 'log10', 'exp'] },
trig: { label: 'Trig', fns: ['sin', 'cos', 'tan', 'asin', 'acos', 'atan'] },
other: { label: 'Other', fns: ['fmod', 'hypot', 'fmax', 'fmin', 'remainder'] }
};
const FN = {
sqrt: { arity: 1, defaults: [64], compute: x => Math.sqrt(x) },
pow: { arity: 2, defaults: [3, 4], compute: (x, y) => Math.pow(x, y) },
cbrt: { arity: 1, defaults: [27], compute: x => Math.cbrt(x) },
floor: { arity: 1, defaults: [4.7], compute: x => Math.floor(x) },
ceil: { arity: 1, defaults: [4.2], compute: x => Math.ceil(x) },
round: { arity: 1, defaults: [4.6], compute: x => cRound(x) },
trunc: { arity: 1, defaults: [5.9], compute: x => Math.trunc(x) },
abs: { arity: 1, defaults: [-3], compute: x => Math.abs(Math.trunc(x)) },
fabs: { arity: 1, defaults: [-5.7], compute: x => Math.abs(x) },
log: { arity: 1, defaults: [2.7183], compute: x => Math.log(x) },
log10: { arity: 1, defaults: [100], compute: x => Math.log10(x) },
exp: { arity: 1, defaults: [1], compute: x => Math.exp(x) },
sin: { arity: 1, defaults: [90], angle: true, compute: x => Math.sin(x) },
cos: { arity: 1, defaults: [0], angle: true, compute: x => Math.cos(x) },
tan: { arity: 1, defaults: [45], angle: true, compute: x => Math.tan(x) },
asin: { arity: 1, defaults: [1], compute: x => Math.asin(x), outAngle: true },
acos: { arity: 1, defaults: [1], compute: x => Math.acos(x), outAngle: true },
atan: { arity: 1, defaults: [1], compute: x => Math.atan(x), outAngle: true },
fmod: { arity: 2, defaults: [7.5, 2], compute: (x, y) => cFmod(x, y) },
hypot: { arity: 2, defaults: [3, 4], compute: (x, y) => Math.hypot(x, y) },
fmax: { arity: 2, defaults: [3, 9], compute: (x, y) => Math.max(x, y) },
fmin: { arity: 2, defaults: [3, 9], compute: (x, y) => Math.min(x, y) },
remainder: { arity: 2, defaults: [5.3, 2], compute: (x, y) => cRemainder(x, y) }
};
let curCat = 'power';
let curFn = 'sqrt';
let angleUnit = 'deg'; // for trig input
const catTabs = wrapper.querySelectorAll('#cat-tabs .chip');
const fnTabsRow = $('#fn-tabs');
const fnArea = $('#fn-area');
const constArea = $('#const-area');
const codeEl = $('#fn-code');
const fieldsEl = $('#fn-fields');
const resultEl = $('#fn-result');
function fmtNum(n) {
if (!isFinite(n)) return String(n);
if (Number.isInteger(n)) return n.toFixed(1);
return (Math.round(n * 1e6) / 1e6).toString();
}
function renderFnTabs() {
fnTabsRow.innerHTML = '';
CATS[curCat].fns.forEach(fn => {
const btn = document.createElement('button');
btn.className = 'chip small' + (fn === curFn ? ' is-active' : '');
btn.textContent = fn + '()';
btn.addEventListener('click', () => { curFn = fn; renderFnTabs(); renderFn(); });
fnTabsRow.appendChild(btn);
});
}
function renderFn() {
const def = FN[curFn];
fieldsEl.innerHTML = '';
const inputs = [];
for (let i = 0; i < def.arity; i++) {
const wrap = document.createElement('span');
const label = document.createElement('label');
label.textContent = def.arity === 2 ? (i === 0 ? 'x' : 'y') : 'x';
const input = document.createElement('input');
input.type = 'number';
input.step = 'any';
input.value = def.defaults[i];
input.addEventListener('input', update);
wrap.appendChild(label);
wrap.appendChild(input);
fieldsEl.appendChild(wrap);
inputs.push(input);
}
if (def.angle) {
const toggleWrap = document.createElement('span');
const degBtn = document.createElement('button');
degBtn.className = 'chip small' + (angleUnit === 'deg' ? ' is-active' : '');
degBtn.textContent = 'degrees';
degBtn.addEventListener('click', () => { angleUnit = 'deg'; renderFn(); });
const radBtn = document.createElement('button');
radBtn.className = 'chip small' + (angleUnit === 'rad' ? ' is-active' : '');
radBtn.textContent = 'radians';
radBtn.addEventListener('click', () => { angleUnit = 'rad'; renderFn(); });
toggleWrap.appendChild(degBtn);
toggleWrap.appendChild(radBtn);
fieldsEl.appendChild(toggleWrap);
}
function update() {
const vals = inputs.map(inp => parseFloat(inp.value) || 0);
let callVals = vals.slice();
if (def.angle && angleUnit === 'deg') {
callVals[0] = vals[0] * Math.PI / 180;
}
const result = def.compute.apply(null, callVals);
let displayResult = result;
let unitNote = '';
if (def.outAngle) {
displayResult = result; // radians
unitNote = ' rad (' + fmtNum(result * 180 / Math.PI) + '\u00b0)';
}
codeEl.innerHTML = '<span class="syn-func">' + curFn + '</span>(' + vals.join(', ') + ')' +
(def.angle ? ' <span style="color:var(--ink-soft);font-size:0.75rem;">// ' + (angleUnit === 'deg' ? vals[0] + '\u00b0 = ' + fmtNum(callVals[0]) + ' rad' : 'radians') + '</span>' : '');
resultEl.textContent = '= ' + fmtNum(displayResult) + unitNote;
}
update();
}
catTabs.forEach(tab => {
tab.addEventListener('click', () => {
catTabs.forEach(t => t.classList.remove('is-active'));
tab.classList.add('is-active');
curCat = tab.dataset.cat;
if (curCat === 'const') {
fnArea.style.display = 'none';
fnTabsRow.style.display = 'none';
constArea.style.display = 'block';
} else {
fnArea.style.display = 'block';
fnTabsRow.style.display = 'flex';
constArea.style.display = 'none';
curFn = CATS[curCat].fns[0];
renderFnTabs();
renderFn();
}
});
});
$('#const-pi').textContent = Math.PI.toFixed(14);
$('#const-e').textContent = Math.E.toFixed(14);
renderFnTabs();
renderFn();
})();
</script>📌 Real Life Use Cases
Game development → Movement, angles, rotations.
Scientific computing → Logarithmic or exponential simulations.
Finance software → Compound interest (with
pow()).Graphics/Animation → Using trigonometry for rotations.
Engineering → Calculations involving
hypot(), roots, trig.
⚠️ Precision Tips
All
math.hfunctions work withdouble.Use
sqrtf(),cosf()etc. forfloat.Use
%.2finprintffor formatting:
printf("%.2f", sqrt(10)); // 3.16