Reducing fractions

I need to write a program that simplifies an array of fractions, converts them into decimal form and then adds them up.
So for 4/8 and 9/15, the output would be 1/2 3/5, 0.5 0.6 and 1.1
Sorry for not showing any work in progress, I'm at loss how to approach it and wondering if you could help.
It's hard to help without any code you've written to solve the problem.

Something is better than nothing, we could point out how to fix any issues you have. But we can't without having an attempt shown.

You ask 10 people how to code something and you'll end up getting 12 (or more) code snippets.
Have you used a struct or a class before? I assume your assignment wants you to make a fraction class?

Have a simple struct like:
1
2
3
4
struct Fraction {
    int numerator;
    int denominator; 
}


Then, you can have an array of Fractions...
Fraction fractions[100];

To simplify a fraction, you need to find the gcd of the numerator and the denominator, and then divide them by that gcd. (Equivalently, but a little less efficiency, you can just loop through all the numbers between the larger number and 2 and see which are divisible using the % operator.)

To print a fraction, you can then do
1
2
Fraction fract {4, 8};
std::cout << fract.numerator << '/' << fract.denominator << '\n';


To convert a fraction to a 'decimal' (floating-point) form,
1
2
double value = static_cast<double>(fract.numerator) / fract.denominator;
std::cout << value << '\n';

Last edited on
Since c++17, there is the gcd() function. See https://en.cppreference.com/w/cpp/numeric/gcd
<ratio> may also be useful.
https://www.cplusplus.com/reference/ratio/ratio_multiply/

depends on if you are expected to hand-roll it or just produce a program to do the job at hand.
Last edited on
Unfortunately the ratio header only supports compile-time ratios.
Ah. Well that is about useless :) Carry on!
Topic archived. No new replies allowed.