Skip to content
C++ project #13Intermediate

Exact Fraction Calculator

A Fraction class that is always in lowest terms, with every arithmetic and comparison operator, decimal and mixed-number input, powers and overflow detection.

Estimated time
~4 hours to build
Files
7 files · 446 lines
Technologies
C++17, <numeric> (std::gcd), <cstdint>, <stdexcept>, Header/source split

Introduction

0.1 + 0.2 isn't 0.3 in floating point, but 1/10 + 2/10 is exactly 3/10. This project builds a rational-number type with operator overloading and class invariants (lowest terms, positive denominator), and shows how careful arithmetic — cross-cancelling, LCM-based addition, checked multiplication — avoids overflow.

Problem statement

Create a calculator that evaluates <a> <op> <b> lines exactly. Operands may be integers, fractions (-7/4), finite decimals (0.125), bracketed mixed numbers ([2 1/3]) or ans. Support + - * /, integer powers (including negative ones), comparisons < > = and sum of a list. Show each result as a fraction, a mixed number and an approximate decimal. Reject zero denominators, division by zero, malformed numbers and results too large for 64-bit integers.

Objectives

  • Maintain a class invariant in every constructor and operation
  • Overload arithmetic, comparison and stream operators
  • Parse several textual formats into one type
  • Detect integer overflow before it happens

Features

  • Always-normalised fractions
  • Decimal and mixed-number input
  • Exponentiation by squaring, negative exponents
  • Overflow and divide-by-zero detection with exceptions

Concepts demonstrated

  • Class invariants
  • Operator overloading
  • Overflow checking
  • Parsing
  • Exceptions

System architecture

Fraction stores int64_t num_, den_; the constructor and every compound operator end with normalise(), which makes the denominator positive and divides by std::gcd. Addition uses the least common multiple of the denominators; multiplication cross-cancels before multiplying. checked_mul and checked_add throw std::overflow_error instead of wrapping. Comparisons reuse subtraction, and equality is exact because both sides are in lowest terms. main.cpp tokenises the line (keeping [...] together) and dispatches on the operator.

Folder structure

TextProject tree
fraction-calculator/
├── README.md
├── Makefile
├── src/fraction.cpp
├── src/fraction.h
├── src/main.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/fraction.h
The Fraction class interface, free operators and pow.
src/fraction.cpp
Normalisation, checked arithmetic, parse (integer / fraction / decimal / mixed), comparisons, printing and exponentiation by squaring.
src/main.cpp
Tokeniser, the ans register, the sum command and result display.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Fraction Calculator ===
> = 5/6 (5/6, ~0.833333)
> = 5
> = -1/12 (-1/12, ~-0.0833333)
> = 1/2 (1/2, ~0.5)
> = 1/4 (1/4, ~0.25)
> = -7/2 (-3 1/2, ~-3.5)
> = -343/8 (-42 7/8, ~-42.875)
> = 9/4 (2 1/4, ~2.25)
> true
> false
> Error: denominator cannot be zero
> Error: division by zero
> = 5/4 (1 1/4, ~1.25)
> Error: 'x' is not a number
> Error: unknown operator '%'
> Error: write: <a> <op> <b>
>
Input
1/2 + 1/3
ans * 6
3/4 - 5/6
[2 1/3] * 3/14
0.125 + 1/8
-7/4 / 1/2
ans ^ 3
2/3 ^ -2
6/8 = 3/4
0.3 > 1/3
1/0 + 1
5 / 0
sum 1/2 1/3 1/6 1/4
1/x + 2
1/2 % 3
1/2 +
quit

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • 1/2 + 1/3 = 5/6; ans * 6 = 5; 3/4 − 5/6 = −1/12.
  • [2 1/3] * 3/14 = 1/2 and -7/4 / 1/2 = −7/2 = −3 1/2.
  • 0.3 > 1/3 is false; 1/0 and 5 / 0 are both rejected.

Common errors

6/8 = 3/4 prints false

Equality by members only works if every fraction is normalised; call normalise() after each operation.

Wrong results with large numbers

Plain int64 multiplication overflows silently; check before multiplying, as checked_mul does.

Possible improvements

  • Parse full expressions with precedence
  • Support repeating decimals like 0.(3)
  • Convert results to continued fractions

Additional challenges

  1. 1Make the class a template over the integer type.
  2. 2Add sqrt that returns an exact result when possible.
  3. 3Implement std::hash<Fraction> and store fractions in an unordered_set.

Built and tested it yourself? Mark it to update your dashboard.