In: Computer Science
Create a function that takes a vector of vectors as an argument. Each inner vector has 2 elements. The first element is the numerator and the second element is the denominator. Return the sum of the fractions rounded to the nearest whole number.
Examples:
sum_fractions({{18, 13}, {4, 5}}) ➞ 2
sum_fractions({{36, 4}, {22, 60}}) ➞ 9
sum_fractions({{11, 2}, {3, 4}, {5, 4}, {21, 11}, {12, 6}}) ➞ 11
Notes Your result should be a number not string.
Code in C++ language
CODE:
#include <bits/stdc++.h>
using namespace std;
//defining sum_fractions function
int sum_fractions (vector<vector<int>>v)
{
// Initialising sum variable to store the sum of the fractions
double sum=0.0;
// storing the size of the vector in size
int size = v.size();
// iterating through all the vector pairs
for(int i=0;i<v.size();i++)
{
// adding the fraction to the sum, typecasting the numerator to double to get accurate results
sum = sum + (double)v[i][0]/v[i][1];
}
// returning the rounded value
return round(sum);
}
SAMPLE TEST CODE:
OUTPUT: