C++

Calculations with Fractions in C++3 min read

DESCRIPTION

Hello,

Fractions are defined here with 64-bit integers.




We make sure that the denominator is always positive.
Special case: indefinite fraction ↔ denominator = 0.

Division-by-zero errors are handled, but beware: no overflow-time overflow checking!

Functions developed (with A, B: fractions; N, D, I: integers):

Manufacturer (with simplification):
Frac (N, D)
Unary operations:
+ A, -A
Assignments:
+ = B, – = B, * = B, / = B
Arithmetic operations:
A + B, A – B, A * B, A / B
A + I, A – I, A * I, A / I
I + A, I – A, I * A, I / A

The simple struct structure is used to facilitate the transcription of code in other programming languages:

To make it a “library” (library software), it is better to use a structure more “complete”, that is to say with protections.

The tests in Fractions.cpp of the Zip show that we can write combinations of arithmetic operations by mixing integers and fractions.

The Val and Out functions are used to “check” calculations.

The last example is the continuous fraction approaching √2:

 

Leave a Comment