In C, is there a difference between integer division a/b and floor(a/b) where both a and b are integers? More specifically what happens during both processes?
Floor division is a normal division operation except that it returns the largest possible integer. This integer is either less than or equal to the normal division result. Floor function is mathematically denoted by this ⌊ ⌋ symbol.
the answer is yes.
Integer Division and the Remainder OperatorInteger division yields an integer result. For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division.
Since in C and C++, as others have said, / is integer division, it will return an int. in particular, it will return the floor of the double answer...
a/b
does integer division. If either a
or b
is negative, the result depends on the compiler (rounding can go toward zero or toward negative infinity in pre-C99; in C99+, the rounding goes toward 0). The result has type int
. floor(a/b)
does the same division, converts the result to double, discards the (nonexistent) fractional part, and returns the result as a double.
floor
returns a double
while a / b
where both a
and b
are integers yields an integer value.
With the correct cast the value is the same.
If typeof
operator existed in C (it does not) we would have:
(typeof (a /b)) floor(a / b) == a / b
EDIT: Now if the question is: is there any difference between:
(double) (a / b)
and
floor(a / (double) b)
the answer is yes. The results differ with respect to negative values.
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