In this shot, we will learn how to use the ratio_less()
function. The ratio_less()
function is available in the <ratio>
header file in C++. This template alias is used to check whether the first ratio object is less than the second ratio object or not and gives the boolean value as a result, i.e., either true or false. The ratio_less()
method compares the simplest forms of the two ratios.
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.
ratio_less()
function is true
.Let’s dive into how the less than inequality check took place.
The ratios and can be represented as and in fractional form, respectively.
Both the ratios are already simplified.
Now, the simplified fractions, i.e., and , are compared.
We can see that the first ratio is less than the second ratio, and we get the final result as true.
ratio
object to be compared for less than inequality with the other ratio object.ratio
object that gets compared for the less than inequality with the previous ratio object.ratio_less()
returns the boolean result after comparison for less than inequality.
If the first ratio object is less than the second ratio object, then ratio_less()
returns true
.
If the first ratio object is not less than the second ratio object, then ratio_less()
returns false
.
Let’s have a look at the code.
#include <iostream>#include <ratio>using namespace std;int main(){typedef ratio<1, 5> ratio_one;typedef ratio<1, 5> ratio_two;if (ratio_less<ratio_one, ratio_two>::value)cout<<"The ratio_one is less than the ratio_two";elsecout<<"The ratio_one is not less than the ratio_two";return 0;}
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 the two ratios.
In line 10, we use the ratio_less()
function inside the if
statement to perform the comparison between the two declared ratios. If the first ratio object is less than the second ratio object, then the if
statement gets executed and displays the message with the result. Here, value
is a member variable of the ratio
class.
In line 12, if the condition doesn’t satisfy, i.e., the first ratio object is not less than the second ratio object, then the else
statement gets executed and displays the message with the result.
We can use the ratio_less()
function to check whether the first ratio object is less than the second ratio object.