271

For example,

int result;

result = 125/100;

or

result = 43/100;

Will result always be the floor of the division? What is the defined behavior?

Lundin
  • 195,001
  • 40
  • 254
  • 396
T.T.T.
  • 33,367
  • 47
  • 130
  • 168
  • 9
    Summary: ***signed* integer division truncates towards zero**. For non-negative results, this is the same as floor (round towards -Infinity). (Beware that C89 doesn't guarantee this, see answers.) – Peter Cordes Nov 07 '17 at 04:19
  • 54
    Everyone keeps saying "truncate toward zero" or "ceiling" or "floor" like the code is making a deliberate decision on which technique to use. If the code could talk it would say `"I just throw the dam fraction part in the trash and move on with life"` – Timothy L.J. Stewart Oct 08 '18 at 03:09
  • 7
    @TimothyL.J.Stewart The "code" is making a deliberate decision. As per the specification, integer division is meant to be T(runcation)-division. Because of this, the modulo/remainder operator is implented differently than if it were in another language, say, Python or Ruby. See [this](https://en.wikipedia.org/wiki/Modulo_operation) for a list of different ways languages do the modulo operator and [this](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf) paper that lists out at least five of the common ways programming languages decide to do div/modulo. – 13steinj Oct 23 '18 at 21:22
  • 6
    @13steinj I'm speaking colloquially per the comments it was turning into a "it's truncate toward zero... no it's floor... no if its negative its ceiling..." sometimes technicalities do not propagate into the future with human memory like we wish, but knowing intuitively that the "fraction part is tossed away" you can derive the technical points. Technicalities are a heavy burden, but intuition is light and refreshing as the wind, I'll carry those far and wide and when necessary I'll know where to start. Like that paper you linked, thank you. – Timothy L.J. Stewart Oct 24 '18 at 00:50
  • I answered [here](https://stackoverflow.com/a/56201161/2001017) with the emphasis on the Euclidean division (inter-play between integer division and modulus operator). – Picaud Vincent May 18 '19 at 17:25
  • Related: doing integer division with rounding to nearest whole integer, instead of truncating: https://stackoverflow.com/questions/2422712/rounding-integer-division-instead-of-truncating/58568736#58568736 – Gabriel Staples Oct 26 '19 at 07:28

6 Answers6

229

Will result always be the floor of the division? What is the defined behavior?

Not quite. It rounds toward 0, rather than flooring.

6.5.5 Multiplicative operators

6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

and the corresponding footnote:

  1. This is often called ‘‘truncation toward zero’’.

Of course two points to note are:

3 The usual arithmetic conversions are performed on the operands.

and:

5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

[Note: Emphasis mine]

user2357112
  • 260,549
  • 28
  • 431
  • 505
dirkgently
  • 108,024
  • 16
  • 131
  • 187
  • 27
    ...unless, of course, you're dividing a negative number by a positive (or v.v.), in which case it'll be the ceiling. – Will A Aug 30 '10 at 17:45
  • 84
    It is neither flooring nor ceiling, it is truncation of fractional part, it is conceptually different! – lornova Aug 30 '10 at 17:48
  • 43
    @Will A: No. It is defined as truncation towards zero. Calling it anything else will just add to confusion so please refrain from doing so. – Martin York Aug 30 '10 at 17:49
  • 50
    At least from a mathematical perspective, truncation towards zero is equivalent to "if > 0 then floor else ceiling." I think just calling it truncation is simpler than calling it floor/ceiling, but either is valid. Regardless, Will A's point is valid: Dirkgently's answer is partially incorrect, since he stated that the OP is right about the result being the floor of the division. – Brian Aug 30 '10 at 18:17
  • 2
    Is this behaviour in C89 as well? I seem to remember modulus is not as rigorously defined. – Philip Potter Aug 30 '10 at 20:32
  • 9
    @Philip Potter: I don't think it was defined in C89, and it isn't in the 1998 C++ standard. In those, of course `(a / b) * b + a % b == a` had to be satisfied, and the absolute value of `a % b` had to be less than `a`, but whether `a % b` was negative for negative `a` or `b` was not specified. – David Thornley Aug 30 '10 at 21:28
  • 2
    Even if it's defined as truncation towards zero, it's still the floor operation in the non-negative case and ceiling operation in the non-positive case. They're equivalent definitions. Which definition is clearer to think about depends on what you're doing. Sometimes it's more convenient to think of it in terms of floor and ceiling, and sometimes it's more convenient to think of it in terms of truncation. – Todd Lehman Aug 18 '14 at 00:21
  • 5
    Why does this have so many upvotes? It gives the wrong answer then quotes the part of the standard that directly contradicts the answer. It doesn't matter if you can define truncation in terms of floor. The answer to the question "Will result always be the floor of the division?" is unequivocally "no" – Tim Seguine Sep 24 '16 at 12:01
  • 3
    Everyone keeps saying "truncate toward zero" or "ceiling" or "floor" like the code is making a deliberate decision on which technique to use. If the code could talk it would say `"I just throw the dam fraction part in the trash and move on with life"` – Timothy L.J. Stewart Oct 07 '18 at 22:43
55

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

Community
  • 1
  • 1
schot
  • 10,958
  • 2
  • 46
  • 71
  • 4
    And C99 draft N1256 foreword paragraph 5 mentions `reliable integer division` as a new language feature. Amazing `*-*`. – Ciro Santilli OurBigBook.com Sep 11 '16 at 08:24
  • Truncation is how most common CPU hardware (e.g. x86) behaves, so it would be crazy to make a different choice. IDK which came first, Fortran semantics or hardware behaviour, but it's not a coincidence that those are the same, too. – Peter Cordes Nov 07 '17 at 04:23
  • 3
    @PeterCordes: Most common CPU hardware could do floored division by most constants faster than they could do truncating division. IMHO, it would have been better for the Standard to say that `expr1 / expr2` and `expr1 % expr2` must be consistent with each other when both instances of `expr1` combine the same objects in the same way, and likewise for `expr2`, but the choice of truncating versus floored division is otherwise Unspecified. That would have allowed more efficient code generation without breaking much compatibility (and implementations could document specific behavior if inclined) – supercat Jun 30 '18 at 20:05
38

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Leonid
  • 22,360
  • 25
  • 67
  • 91
27

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Gareth Williams
  • 623
  • 5
  • 9
  • 4
    I agree with the comment wondering whether having (neg % pos) go negative is ever useful? On a related note, I wonder if the required arithmetically-incorrect behavior in some cases of "unsignedvar > signedvar" is ever useful? I can understand the rationale for not requiring always-correct behavior; I see no rationale for requiring wrong behavior. – supercat Aug 30 '10 at 18:34
  • 8
    +1 for an excellent reference on why flooring is the correct behavior for integer division (contrary to C's definition, which is broken and almost-never useful). – R.. GitHub STOP HELPING ICE Aug 30 '10 at 19:19
  • @supercat Consider: `filtered = (k - 1) * filtered + value + carry; carry = filtered % factor; filtered /= factor`, iterated with changing values of `value`. It makes a nice integer approximation to a first-order lowpass filter with time constant `k`... but it's only symmetric if division is truncating and `carry` gets negative values. Both behaviors for division come in handy from time to time. – hobbs Dec 21 '17 at 15:01
  • 1
    @hobbs: I don't think the above code would behave cleanly when signals cross zero. If `div` is a floored division operator and `factor` is odd, then `filtered += (filter+(factor div 2)) div factor` would yield clean and symmetrical behavior for all values up to `INT_MAX-(factor div 2)`. – supercat Dec 21 '17 at 18:35
  • @supercat it does work though; that code is only slightly distilled from something I've had running in the controller of an atomic clock for a while. – hobbs Jan 16 '18 at 22:11
  • @hobbs: For any given value of `filtered` `carry`, and `factor`, there will be "factor" values that yield each possible output value that is strictly between the minimum and maximum possible outputs, except that there will be `2*factor+1` values that yield an output value of zero. – supercat Jan 17 '18 at 02:25
13

Will result always be the floor of the division?

No. The result varies, but variation happens only for negative values.

What is the defined behavior?

To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)

For positive values they are the same

int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0

For negative value this is different

int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0
Mohamed El-Nakeep
  • 6,580
  • 4
  • 35
  • 39
4

I know people have answered your question but in layman terms:

5 / 2 = 2 //since both 5 and 2 are integers and integers division always truncates decimals

5.0 / 2 or 5 / 2.0 or 5.0 /2.0 = 2.5 //here either 5 or 2 or both has decimal hence the quotient you will get will be in decimal.

adi1ya
  • 404
  • 1
  • 7
  • 10