Question: In C++ create a class named fraction which will represent a new data type corresponding to fractions. Your class should create the following private members:
In C++ create a class named fraction which will represent a new data type corresponding to fractions. Your class should create the following private members:
- Integers n and d corresponding to the numerator and denominator of the fraction
- A function gcd which returns the greatest common divisor of 2 integers (to help you reduce the fraction).
And the following public member functions:
- 3 constructors which will create any fraction when declared with 2 integers, will create a/1 when declared with 1 integer, and will create 0/1 when declared with no integers.
- num which returns the numerator of the fraction
- denom which returns the denominator of the fraction
- reduce which reduces the fraction to its lowest terms (using the gcd function above). This function changes the value of n and d appropriately.
- convert which returns a double representing the fraction (i.e. 3/4 becomes 0.75)
- show which displays the fraction (as a fraction) to the monitor (a fraction like a/1 should be displayed as a, and a fraction like 0/b should be displayed as 0).
Your main function should (in this order):
(a) Test all three constructors using show
(b) Test num and denom
(c) Test reduce
(d) Test convert
(e) If you do the bonus (see below), test these.
Bonus: Create 4 functions which can add, subtract, multiply, or divide fractions. The answer calculated should be in lowest terms (like 3/4 instead of 6/8).
Please comment and explain declaration if possible. Thanks .
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
