5

Can I be sure that an odd number in C++ should always return floor of the result when divided in such a way that there is a remainder or are there any exceptions to this? I mean:

int x = 5;
x = x/2;
cout<<x;      //2
Straightfw
  • 2,143
  • 5
  • 26
  • 39

3 Answers3

5

yes. you can be sure of that in c++

ISO/IEC N3485(working draft) says in 5.6.4

The binary / operator yields the quotient, and the binary % operator yields 
the remainder from the division of the first expression by the second.
   If the second  operand of / or % is zero the behavior is undefined. 
For integral operands the / operator yields the algebraic quotient with any 
fractional part discarded;81 if the quotient a/b is representable in the type 
of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both 
a/b and a%b is undefined.
Koushik Shetty
  • 2,146
  • 4
  • 20
  • 31
2

Integer division is handled as a floor operation in C/C++.

You get 2 in the above example since the real answer 2.5 can't be represented.

Some more verbose answers here

Community
  • 1
  • 1
Guvante
  • 18,775
  • 1
  • 33
  • 64
2

Yes; division between integers is always integral division in C++:

[C++11 5.6/4]: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055