Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C integer division and floor

Tags:

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?

like image 969
CodeKingPlusPlus Avatar asked Sep 02 '12 22:09

CodeKingPlusPlus


People also ask

Is integer division same as floor?

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.

Is there a floor division in C?

the answer is yes.

Is there integer division in C?

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.

Is integer division the same as floor C++?

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...


2 Answers

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.

like image 144
Pete Becker Avatar answered Sep 20 '22 21:09

Pete Becker


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.

like image 23
ouah Avatar answered Sep 18 '22 21:09

ouah