How to use the ratio_less() function in C++
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.
What is a ratio?
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 that the first ratio is and the second ratio is .
- The result of the
ratio_less()function istrue.
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.
Parameters
- Ratio 1: A
ratioobject to be compared for less than inequality with the other ratio object. - Ratio 2: Another
ratioobject that gets compared for the less than inequality with the previous ratio object.
Return value
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()returnstrue. -
If the first ratio object is not less than the second ratio object, then
ratio_less()returnsfalse.
Code
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;}
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 the two ratios.
-
In line 10, we use the
ratio_less()function inside theifstatement to perform the comparison between the two declared ratios. If the first ratio object is less than the second ratio object, then theifstatement gets executed and displays the message with the result. Here,valueis a member variable of theratioclass. -
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
elsestatement 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.