A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
modf takes a double and a pointer to a double. It splits the value into its integer part and its fractional part, storing the integer part through the pointer and returning the fractional part. Both parts have the same sign as the input. This is the floating-point equivalent of div: one operation, two results. It is useful in financial calculations, signal processing, and any code that needs to separate whole units from remainders.
#include <stdio.h>#include <math.h>int main(void) {double values[] = {3.14159, -2.71828, 42.0, 0.001};int n = 4;for (int i = 0; i < n; i++) {double int_part;double frac_part = modf(values[i], &int_part);printf("modf(%10.5f) -> int: %6.0f, frac: %8.5f\n",values[i], int_part, frac_part);}return 0;}
The integer part is stored through the pointer. The fractional part is returned. Both carry the sign of the original value. -2.71828 splits into -2 and -0.71828, not -2 and +0.28172. The sum of the two parts always equals the original value. This invariant is useful for verification in numerical code.
modf is a small utility that eliminates manual casting and subtraction. One call, two results, sign preserved. Next: fmod, the floating-point remainder function that generalizes the % operator to doubles.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.