How to use the ratio_subtract() function in C++
In this shot, we will learn how to use the ratio_subtract() function. This template alias is used to subtract two ratios.
The
ratio_subtract()function is available in the<ratio>header file in C++.
What is a ratio?
A ratio is a representation of a fraction in which the numerator and denominator are differentiated by a colon (:) symbol. The numerator and denominator can be of float data type.
Let’s understand with the help of an example. Suppose that the first ratio is 1 : 3 and the second ratio is 5 : 2.
So, the result of the ratio_subtract() function on these two ratios gives -13 : 6. Let’s explore how the addition took place.
-
First, we need to find the
of the denominators of the two fractions which will be the denominator of the subtraction.LCM Lowest Common Multiple -
The LCM of 3 and 2 is 6.
-
Now subtraction = = .
Parameters
The ratio_subtract() method takes the following parameters:
Ratio1: Aratioobject for addition.Ratio2: Anotherratioobject to perform the addition with the firstratioobject.
Return value
This function returns the result of the subtraction in the simplest form. It returns two member constants:
num: The simplified numerator of the ratio after the subtraction of the two ratios.den: The simplified denominator of the ratio after the subtraction of the two ratios.
Code
Let’s have a look at the code.
#include <iostream>#include <ratio>using namespace std;int main(){typedef ratio<1, 3> ratio1;typedef ratio<5, 2> ratio2;typedef ratio_subtract< ratio1, ratio2 > diff;cout << "The ratio after addition is : ";cout << diff::num << "/" << diff::den;return 0;}
Explanation
-
In lines 1 and 2, we import the required header files.
-
In line 5, we make a
main()function. -
From lines 7 and 8, we declare two ratios.
-
In line 10, we perform the subtraction of the two declared ratios by using the
ratio_subtract()function. -
In line 12, we display a message regarding the result.
-
In line 13, we display the numerator and denominator by accessing them through the sum variable and display the result.
In this way, we can use the ratio_subtract() function to add two ratios and get the subtraction in the simplest form.