Rationalise (Canonise) the Fractions before Subtraction
Normally before fractions are subtracted, they are rationalised;
i.e., they are put in a form where their denominators become
the same. This same denominator is the LCM of the
denominators of all the separate fractions.
After this is done, the new numerators can then be subtracted.
Steps for Subtraction of Fractions C++ code
The following steps will guide us in writing our code.
Let's illustrate with
7/4 - 2/5
Step 1:
Find the LCM of the denominators.
⇒ LCM of 4 & 5 = 20
Step 2:
In a turn by turn fashion, divide the found LCM from Step 1
by each denominator, multiplying the quotient by the corresponding numerator.
⇒
((7 x 5) - (2 x 4))/20
= (35 - 8)/20
Step 3:
Go ahead and subtract the numerators.
⇒
27/20
Create a new class file;
call it SubtractFraction
Type out the adjoining C++ code for subtracting fractions.
Note: You can comment out the AddFraction C++ object
code in the main class from the previous lesson or simply continue from where it stopped.
So!
Feel free to try out your own set of numerators and denominators for fractional subtraction.
C++ code for SubtractFraction Header File
#pragma once
#include "AddFraction.h"
class SubtractFraction : public AddFraction {
public:
SubtractFraction(vector<unsigned>, vector<unsigned>);
virtual ~SubtractFraction();
void doSubtract(void);
};
SubtractFraction Class File
#include "stdafx.h"
#include "SubtractFraction.h"
SubtractFraction::SubtractFraction(vector<unsigned> num, vector<unsigned> denom) : AddFraction(num, denom) {
}
void SubtractFraction::doSubtract() {
canonizeFraction();
answer = new_numerators[0];
for (unsigned i = 1; i < new_numerators.size(); i++) {
answer -= new_numerators[i];
}
}
SubtractFraction::~SubtractFraction() {
}
Main class
#include "stdafx.h"
#include "SubtractFraction.h"
#include <iostream>
#include <vector>
#include <exception>
using namespace std;
int main() {
cout << "\n Welcome to our demonstration sequels";
cout << "\n Hope you enjoy (and follow) the lessons.\n\n";
vector<unsigned> numerators;
vector<unsigned> denominators;
try {
numerators = { 9, 3, 5, 7 };
denominators = { 2, 4, 12, 18 };
cout << "\n Solving:\n";
for (unsigned n : numerators) {
printf("%13u", n);
}
printf("\n%12s", " ");
for (unsigned i = 0; i < numerators.size() - 1; i++) {
cout << "- - ";
}
printf("%2s\n", "-");
for (unsigned d : denominators) {
printf("%13u", d);
}
cout << "\n";
SubtractFraction sub_fract(numerators, denominators);
sub_fract.doSubtract();
printf("\n%26u\n", sub_fract.answer);
printf("%26s\n", "Answer = -");
printf("%26u\n", sub_fract.LCM);
cout << "\n\n";
} catch (exception& e) {
cout << "\n" << e.what() << "\n";
}
return 0;
}