In this shot, we will learn how to use the ratio_add()
function. This template alias is used to add the two ratios.
The
ratio_add()
function is available in<ratio>
header file in C++.
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_add()
function on these two ratios gives the result as 17 : 6. Let’s dive into how the addition took place.
First, we need to find the
The LCM of 3 and 2 is 6.
Now addition = $\frac{(1*2+5*3)}{6}$ = $\frac{17}{6}$
The ratio_add()
method takes the following parameters:
Ratio1
: A ratio
object for addition.Ratio2
: Another ratio
object to perform the addition with the first ratio
object.This function returns the result of addition in the simplest form. It returns two member constants:
num
: The simplified numerator of the ratio after the addition of the two ratios.den
: The simplified denominator of the ratio after the addition of the two ratios.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_add< ratio1, ratio2 > sum; cout << "The ratio after addition is : "; cout << sum::num << "/" << sum::den; return 0; }
In lines 1 and 2 we imported the required header files.
In line 5 we made a main()
function.
From lines 7 and 8 we declared two ratios.
In line 10 we performed the sum of the two declared ratios by using ratio_add()
function.
In line 12 we displayed a message regarding the result.
In line 13 we displayed the numerator and denominator by accessing them through the sum variable and displayed the result.
In this way, we can use the ratio_add()
function to add two ratios and get the addition in the simplest form.
RELATED TAGS
CONTRIBUTOR
View all Courses