Skip to main content
Contents Index
Search Book
Search Results:
No results.
Readability settings Prev Up Next
\(\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
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.
Activity 25.3 .
Whatβs the best way to go about that?
admin ..... open in new window
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.
Activity 25.5 .
Letβs try to write a function that prints a fraction.
admin ..... open in new window
Subsection 25.3.6 Add-Fractions Function
Activity 25.6 .
Now letβs try our luck with a function that adds two fractions...
admin ..... open in new window
Subsection 25.3.7 Enter-Fraction Function
Activity 25.7 .
Now we need a function that allows the user to enter a fraction. Be sure to prevent the user from entering a denominator of zero!
admin ..... open in new window
Subsection 25.3.8 Multiplying Fractions
Multiplying two fractions is now easy!
Activity 25.8 .
Letβs multiply two fractions!
admin ..... open in new window
Subsection 25.3.9 Additional Steps
Activity 25.9 .
What else do we need to make our fraction calculator work?
admin ..... open in new window