Course outline · 0% complete

0/27 lessons0%

Course overview →

Arithmetic, Integer Division, and Casting

lesson 2-2 · ~11 min · 5/27

Integer division is not a C++ quirk to memorize — CPUs have separate circuits for integer and floating-point math, and C++ maps / directly onto whichever instruction the operand types select. Knowing which one you are invoking is the entire lesson, and it matters in practice: an average that silently comes out 3 instead of 3.5 corrupts results without crashing anything, which makes it one of the hardest bug types to notice.

Operators you already know, one trap you do not

+ - * / % work as in Python, with one huge exception:

Dividing two ints throws away the decimal part.

7 / 2      // 3   (int / int = int, truncated toward zero)
7.0 / 2    // 3.5 (if either side is a double, the result is a double)
7 % 2      // 1   (remainder, ints only)

Python's / always gives a float and // truncates. C++ has only /, and it decides based on the types of its operands. This is the number one beginner bug in C++ arithmetic.

Also familiar from Python: x += 5, x -= 2, x *= 3. New: x++ adds 1 to x, x-- subtracts 1. There is no ** power operator, use std::pow(a, b) from <cmath>.

Code exercise · cpp

Run this and study each line of output. Same numbers, different types, different answers.

Casting: converting between types on purpose

Sometimes both values are ints but you want real division. Cast one operand to double:

int total = 7, count = 2;
double avg = static_cast<double>(total) / count;   // 3.5

static_cast<T>(value) is the modern C++ cast: explicit, searchable, and checked by the compiler. You may see C-style casts like (double)total in old code. They work, but prefer static_cast.

Casts also go the other way, and truncate:

double price = 9.99;
int dollars = static_cast<int>(price);   // 9, the .99 is dropped

Some conversions happen implicitly (int → double is safe and automatic). Narrowing ones (double → int) are where you should be explicit, so readers know the data loss is intentional.

Quiz

int a = 9, b = 4. What does `std::cout << a / b;` print?

Code exercise · cpp

Your turn. Read two ints (points scored and games played) and print the true decimal average. With input `7 2` the output must be exactly `Average: 3.5`. You will need a cast, otherwise you get 3.

Code exercise · cpp

Your turn: total is 17 points over count = 4 games. Compute the true average 4.25 (not 4) into the variable avg and print it. You will need a cast.