Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an odd number always return floor when divided with a remainder?

Tags:

c++

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
like image 390
Straightfw Avatar asked Apr 18 '13 16:04

Straightfw


2 Answers

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.
like image 81
Koushik Shetty Avatar answered Oct 06 '22 00:10

Koushik Shetty


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.

like image 42
Lightness Races in Orbit Avatar answered Oct 05 '22 23:10

Lightness Races in Orbit