-1
5%10/2

I know that the % sign shows the remainder, so the operation should give 2.5 because the remainder of 5%10 is 5. So then 5/2 is 2.5. But it gives me 2.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ROBOTICS
  • 3
  • 1

2 Answers2

2

In C and C++, there's a difference between integer and floating-point division. When you divide 2 integer values, you get the result rounded down, so you get 2.5 instead of 2. If you want 2.5, you should cast one of the operands to a float or just use a float/double literal:

std::cout << ((double) (5 % 10) / 2) << std::endl; // double cast
std::cout << (5 % 10 / 2.0) << std::endl; // double literal
Aplet123
  • 33,825
  • 1
  • 29
  • 55
2

This comes from integer division.

5 % 10 / 2 =
  5    / 2

Integer division returns you the floor of the result:

5 / 2 = 2.5
floor(2.5) = 2

Floor of the result means you round the result to the integer value immediatly smaller to the value you obtained (if this value is not already an integer).

3 / 2 = 1     (since floor(1.5) = 1)
7 / 3 = 2     (since floor(2.33..) = 2)
10 / 9 = 1    (since floor(1.11..) = 1)
...
Daniel
  • 7,357
  • 7
  • 32
  • 84