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
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
#include <iostream>
int main() {
int n = 2;
n++;
std::cout << (n) << '\n';
}
3
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.
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
#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;
}
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.