A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
C provides four rounding functions in math.h, and they are not interchangeable. floor rounds toward negative infinity. ceil rounds toward positive infinity. trunc rounds toward zero. round rounds to the nearest integer, with halfway cases rounding away from zero. The differences matter for negative numbers and for values exactly at .5. Choosing the wrong one gives you a result that is off by one, which in financial code or array indexing is a bug.
#include <stdio.h>#include <math.h>int main(void) {double values[] = {2.3, 2.5, 2.7, -2.3, -2.5, -2.7};int n = 6;printf("%-8s %8s %8s %8s %8s\n", "Value", "floor", "ceil", "trunc", "round");printf("%-8s %8s %8s %8s %8s\n", "-----", "-----", "----", "-----", "-----");for (int i = 0; i < n; i++) {double v = values[i];printf("%-8.1f %8.1f %8.1f %8.1f %8.1f\n",v, floor(v), ceil(v), trunc(v), round(v));}return 0;}
Look at -2.5. floor gives -3 (toward negative infinity). ceil gives -2 (toward positive infinity). trunc gives -2 (toward zero). round gives -3 (away from zero at the halfway point). Four different answers for the same input. The function you choose encodes a policy decision about how to handle the fractional part.
#include <stdio.h>#include <math.h>int main(void) {double position = 3.7;int arr[] = {10, 20, 30, 40, 50};int idx_floor = (int)floor(position);int idx_round = (int)round(position);int idx_trunc = (int)trunc(position);printf("position = %.1f\n", position);printf("floor -> arr[%d] = %d\n", idx_floor, arr[idx_floor]);printf("round -> arr[%d] = %d\n", idx_round, arr[idx_round]);printf("trunc -> arr[%d] = %d\n", idx_trunc, arr[idx_trunc]);return 0;}
floor and trunc agree for positive values. They diverge for negative values. round gives the nearest index. The choice depends on your interpolation strategy. In graphics, floor is standard for texture sampling. In statistics, round is standard for binning. Know which one you need.
Four functions. Four rounding policies. The names are short. The differences are significant. Pick the one that matches your mathematical intent, not the one that happens to give the right answer for your test case. Next: stdarg.h, for writing functions that accept a variable number of arguments.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.