Skip to main content

Section A.5 Integer Division and Casting

In Python, 5 / 3 is 1.6666666666666667. In C, dividing one integer by another gives an integer:
int a = 5;
int b = 3;
int q = a / b;              // q is 1: integer division
int r = a % b;              // r is 2: the remainder
float x = a / b;            // x is 1.0: still integer division
float y = (float)a / b;     // y is about 1.666667: a is cast to a float first
int z = (int)y;             // z is 1
C does not round; it cuts off the fractional part. For positive numbers this is Python’s //. For negative ones the two differ: C cuts toward zero, so -7 / 2 is -3 in C, while Python’s -7 // 2 rounds down to -4.
In the line that computes x, the type of the variable on the left does not matter. The division happens first, between two integers, and only its result, 1, is converted to 1.0. To get a fractional result, one of the values in the division has to be converted, or cast, to a float before dividing. Casting is done by placing the data type to which we want to convert, in parentheses, in front of the value, as in (float)a. A cast to int cuts off the fractional part in the same way.
Since we avoid float, the more useful habit is to keep the arithmetic in integers and do the division last. Expressing 3 out of 8 as a percentage shows the difference.
int done  = 3;
int total = 8;
int wrong = done / total * 100;     // 0:  3 / 8 is already 0
int right = done * 100 / total;     // 37: 300 / 8, fraction cut off
Multiplying first keeps the precision, as long as the product still fits in the type.

Check Your Understanding Check Your Understanding

1.

What value does avg hold after these lines run?
int sum = 17;
int n   = 4;
int avg = sum / n;
  • 4
  • Correct. 17 divided by 4 is 4.25, and integer division cuts off the fractional part.
  • 4.25
  • That is Python’s answer to 17 / 4. In C both values are integers, so the division is integer division, and an int cannot hold 4.25 in any case.
  • 5
  • C does not round to the nearest integer; it cuts off the fractional part, so 4.25 becomes 4.
  • 1
  • 1 is the remainder, 17 % 4. The / operator gives the quotient.