liveBook · Manning

Rational number

As explained in 100 C++ Mistakes and How to Avoid Them

A rational number is a number expressible as a ratio of two integers with a nonzero denominator.

A rational number is a ratio of two integers with a nonzero denominator. Modeling it as a class requires honoring that invariant: doubles are the wrong representation, and division by zero must be rejected. section 7.4

The naïve class makes calculations awkward by offering plus and times methods instead of expected operators. It also exposes setters, permits invalid state, and hides bugs behind code that initially looks reasonable. A safer design stores integers, validates the denominator, reduces the ratio, and supports +, *, and stream output directly. section 7.4

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Examines representation, invariants, invalid states, mutability, arithmetic, and interface design through contrasting implementations.
Examples
Contrasts naïve and corrected C++ Rational class listings, including reduction, addition, multiplication, and output.
What it assumes
Assumes basic C++ classes and arithmetic while teaching rational-number representation and class-interface consequences.
What you can do after
Apply integer representation, invariant validation, reduction, and intuitive operators when maintaining a Rational class.
How it connects
Connects rational numbers with class invariants, immutability, operator overloading, integer arithmetic, and division-by-zero validation.

Also explained in

Compare how 3 books explain rational number →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.