Lesson contents

C++ — Variables, constants, and integer arithmetic

C++ integer arithmetic can store prices in cents. With nonnegative amounts, division by 100 gives whole dollars and the remainder gives the cents to format.

A simple example

Change a stored number

  1. Start with n starts at 2
  2. Do this Add 1 to n
  3. Result 3
After the assignment, reading the same variable gives its new value.
lesson.cpp
#include <iostream>

int main() {
    int n = 2;
    n++;
    std::cout << (n) << '\n';
}
Output
3
Advertisements

Calculate a receipt in cents

constexpr records a compile-time unit price. Both operands of division are integers, so the quotient is integral. setw applies to the next field, letting the remainder print as two digits.

Notebooks: 3 × 125¢ = 375¢. Delivery: 50¢. Amount to pay: 425¢.
Check a stationery order

A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <iomanip>

int main() {
    constexpr int priceCents = 125;
    int quantity = 3;
    int total = priceCents * quantity + 50;
    std::cout << total / 100 << '.' << std::setfill('0') << std::setw(2)
              << total % 100 << '\n';
    return 0;
}
Output
4.25

Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.

Try it yourself

What happens if each item costs 101 cents?

Check your answer

Three items plus delivery cost 353 cents, so the output becomes 3.53.

C++ language and library reference

Related tags

  • C++
  • integers
  • variables
  • arithmetic