I took a quiz in my CS class today and got a question about the modulo operator wrong because I didn't know about the availability of % in C, I've been using fmod()
. Why do both exist? Is one better/faster or do they just deal with different data types?
modulo division
using %
operator in C only works for integer operands and returns an integer remainder of the division.
The function fmod
accepts double
as arguments meaning that it accepts non-integer values and returns the remainder of the division.
Additional note on fmod: how is the remainder calculated in case of double
operand? Thanks @chux for showing the documentation on how fmod calculates the remainder of a floating point division.
The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated.
The returned value has the same sign as x and is less or equal to y in magnitude.
On the other hand, when the modulo division binary operator (%) was first designed, it was determined by the language designers that it would only support operands of 'integer' types because technically speaking, the notion of 'remainder' in mathematics only applies to integer divisions.
It's because %
is an integer operator, and fmod
stands for floatmod
and is used for floating point numbers.
Why do both exist?
Because they may have computed different results, even with the same values. These differences may occur with negative values. In essence fmod()
and %
were different mathematical functions.
fmod(x,y)
, since C89, had the result "the result has the same sign as x and magnitude less than the magnitude of y".
i%j
was not so singularly defined. See Remainder calculation for the modulo operation. This allow code to use existing variant processors effectively. The div()
function was created to address this variability. Ref
By C99 they compute the same for the same values. Future C could allow 123.4 % 56.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With