# Ratio manipulation in C++ with examples

Hello everyone, in this tutorial, we will be studying ratio manipulation in C++. C++ has a header file separately to deal with operations related to fractions. There are many template aliases for ratio manipulation.

## Ratio manipulation in C++

We can perform addition, subtraction, multiplication, and division operation on fractions using <ratio> header file. Let’s discuss these operations one by one.

### Adding ratios

In order to add two ratios, we use **ratio_add** template alias as you can see in the below program. The output given by this is in the simplest form. It returns two values *num* and *den* respectively. *num *represents the numerator and *den* represents the denominator. Have a look at this code.

#include <iostream> #include <ratio> using namespace std; int main() { typedef ratio<1, 4> r1; typedef ratio<1, 8> r2; typedef ratio_add<r1, r2> r3; cout << "Result of 1/4 + 1/8 is: " << r3::num << "/" <<r3::den; return 0; }

The output of the above program:

Result of 1/4 + 1/8 is: 3/8

### Subtracting ratios

As we used ratio_add template alias for the addition of two fractions, similarly we can use **ratio_subtract **subtract one ratio from another. Again the output is in the simplest form. The return values are *num* and *den* respectively.

See the below code.

#include <iostream> #include <ratio> using namespace std; int main() { typedef ratio<1, 4> r1; typedef ratio<1, 8> r2; typedef ratio_subtract<r1, r2> r3; cout << "Result of 1/4 - 1/8 is: " << r3::num << "/" <<r3::den; return 0; }

Output:

Result of 1/4 - 1/8 is: 1/8

### Multiplying ratios

To get the multiplication of two fractions or ratios we can use ratio_multiply. The below code explains the working of this template alias. The return values are the same as in the above two operations.

#include <iostream> #include <ratio> using namespace std; int main() { typedef ratio<1, 4> r1; typedef ratio<1, 8> r2; typedef ratio_multiply<r1, r2> r3; cout << "Result of 1/4 * 1/8 is: " << r3::num << "/" <<r3::den; return 0; }

Output:

Result of 1/4 * 1/8 is: 1/32

### Division of ratios

To divide a ratio by another ratio we have to use ratio_divide template alias. It returns the same values as the above and the result is in the simplest form. See the code.

#include <iostream> #include <ratio> using namespace std; int main() { typedef ratio<1, 4> r1; typedef ratio<1, 8> r2; typedef ratio_divide<r1, r2> r3; cout << "Result of (1/4) / (1/8) is: " << r3::num << "/" <<r3::den; return 0; }

Output:

Result of (1/4) / (1/8) is: 2/1

Thank you. Hope it was helpful.

Also read: Fraction Module in Python

## Leave a Reply

You must be logged in to post a comment.