Introduction / Context:
Unlike integer division, floating-point division in C/C++ uses library functions to compute the remainder. The operator '%' is defined only for integers, so you must select the proper function when working with doubles or floats. This question checks whether you know the standard library tool for floating-point remainders.
Given Data / Assumptions:
- Operands are non-integers: 3.14 and 2.1 (double by default).
- We want the remainder r such that 3.14 = q * 2.1 + r with r having the same sign as the dividend for fmod.
- Standard C headers: / .
Concept / Approach:
- Operator '%' applies to integers only; using it with floating types is a compile-time error.
- 'fmod(x, y)' returns the floating remainder of x / y following the definition r = x - trunc(x / y) * y.
- 'modf(x, &intpart)' splits a floating-point number into fractional and integral parts; it is not a remainder function.
Step-by-Step Solution:
Select the correct API: 'fmod(3.14, 2.1)'.Compute conceptually: r = 3.14 - trunc(3.14/2.1) * 2.1.Identify that '%' with doubles is illegal; 'modf' does something different entirely.
Verification / Alternative check:
C also offers 'remainder(x, y)' which returns r = x - rint(x/y) * y with possibly different sign/ magnitude conventions; the prompt specifically expects 'fmod'.
Why Other Options Are Wrong:
- 3.14 % 2.1: Illegal for floating types.
- modf(3.14, 2.1): Wrong signature and purpose; 'modf' requires a pointer for the integer part.
- Remainder cannot be obtained: False; use 'fmod'.
- remainder(3.14, 2.1): Different function and behavior; not the canonical answer here.
Common Pitfalls:
- Confusing 'modf' with modulo operations.
- Assuming '%' works for floats in C/C++ as in some languages; it does not.
Final Answer:
rem = fmod(3.14, 2.1);
Discussion & Comments