Skip to main content

Section 25.3 The Fraction Calculator Using Structures

Subsection 25.3.1 Define a New Data Type

Remember our fraction calculator? We’ll start rewriting it using structures now.

Activity 25.1.

Let’s start by defining a new data type fraction_t, designed to store the numerator and denominator of a fraction (as integers). Try implementing this below:

admin.....open in new window

Subsection 25.3.2 Declare the Variables

Activity 25.2.

Now that we have our fraction type, let’s declare two variables, frac1 and frac2, of this type, and make them correspond to the fractions \(\frac{5}{3}\) and \(\frac{-2}{5}\text{.}\)

admin.....open in new window

Subsection 25.3.3 Print the Fractions

Now let’s see if we can print out these fractions.

Subsection 25.3.4 Adding Fractions

Activity 25.4.

Since we are working on a fraction calculator, how would we go about adding these two fractions? Let’s store the result in a third variable, result. Can we simply say the following?
result = frac1 + frac2

admin.....open in new window

Subsection 25.3.5 Print-Fraction Function

You can see that it would be great to write some functions in order to re-use our code.

Subsection 25.3.6 Add-Fractions Function

Subsection 25.3.7 Enter-Fraction Function

Subsection 25.3.8 Multiplying Fractions

Multiplying two fractions is now easy!

Subsection 25.3.9 Additional Steps