Related Tags

c++
ratio
communitycreator

# How to use the ratio_divide() function in C++

Harsh Jain

In this shot, we will learn how to use the ratio_divide() function. The ratio_divide() function is available in the <ratio> header file in C++. This template alias is used to divide the two ratios.

### 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 the float data type.

Let’s understand with the help of an example. Suppose that the first ratio is 10 : 3 and the second ratio is 5 : 2. So, the result of the ratio_divide() function on these two ratios gives the result of 4 : 3. Let’s dive into how the division took place.

The ratio 10 : 3 and 5 : 2 can be represented as $\frac{10}{3}$ and $\frac{5}{2}$ in the fractional form, respectively.

Now, the division = $\frac{10}{3}$ / $\frac{5}{2}$ = $\frac{10 * 2}{3 * 5}$ = $\frac{20}{15}$

Now, after simplification of $\frac{20}{15}$ we get $\frac{4}{3}$. So, this is the final result of division.

### Parameters

The ratio_divide() method takes the following parameters:

• Ratio 1: A ratio object which behaves as a dividend in the division.
• Ratio 2: Another ratio object which behaves as a divisor for the dividend above in the division.

### Return

It returns the result of the division in the simplest form. It returns two member constants:

• num: The simplified numerator of the ratio after the division of the two ratios.
• den: The simplified denominator of the ratio after the division of the two ratios.

### Code

Let’s have a look at the code.

#include <iostream>
#include <ratio>
using namespace std;

int main()
{
typedef ratio<10, 3> r1;
typedef ratio<5, 2> r2;
typedef ratio_divide< r1, r2 > division;

cout << "The ratio after division is : ";
cout << division::num << "/" << division::den;
cout << endl;

return 0;
}

Use ratio_divide() function in C++

### Explanation

• In lines 1 and 2 we imported the required header files.
• In line 5 we made a main() function.
• In lines 7 and 8 we declared two ratios.
• In line 10 we perform the division between the two declared ratios by using the ratio_divide() 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 division variable and displayed the result.

So, this is how to use the ratio_divide() function to divide the two ratios and get the division in the simplest form.

RELATED TAGS

c++
ratio
communitycreator

CONTRIBUTOR

Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time