In this shot, we will learn how to use the ratio_equal()
function. This template alias is used to check the equality between the two ratios and gives the boolean value as a result i.e., either true
or false
. The comparison is done between the simplest form of the two ratios by the ratio_equal()
method.
The
ratio_equal()
function is available in the<ratio>
header file in C++.
A ratio is a representation of a fraction in which the numerator and denominator are differentiated by the colon (:) symbol. The numerator and denominator can be of float
data type.
Let’s understand with the help of some examples. Suppose we have the following ratios:
The result of the ratio_equal()
function on comparison for equality of these two ratios gives the result as true
.
Let’s explore how the equality check took place.
The ratios 1 : 5 and 5 : 25 can be represented as and in fractional form respectively.
The ratio is itself a simplified form. on simplification gives .
Now, the simplified fractions and are compared for equality. So, the final result is true.
The ratio_equal()
method takes the parameters below:
Ratio1
: A ratio
object which is to be compared for equality with the other ratio object.Ratio2
: Another ratio
object which gets compared for equality with the previous ratio object.It returns the Boolean result after comparison for equality.
If the ratio objects are equal then it returns true
.
If the ratio objects are not equal then it returns false
.
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;if (ratio_equal<ratio1, ratio2>::value)cout<<"Ratio 1 and Ratio 2 are equal";elsecout<<"Ratio 1 and Ratio 2 aren't equal";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 comparison between the two declared ratios by using the ratio_equal()
function as a condition inside the if
statement. If the two ratio objects are equal then the if statement gets executed and displays the message regarding the result.
In line 12, if the condition doesn’t satisfy i.e., the two ratio objects are not equal, then the statement gets executed and displays the message regarding the result.
In this way, we can use the ratio_equal()
function to check whether the two ratios are equal or not.