-4

In this program, the user is asked for 4 integers that represent two fractions.

First ask for the numerator of the first and then the denominator. Then ask for the numerator and denominator of the second.

The program should add the two fractions and print out the result.

I can't figure out how to add the fractions together

public class AddFractions extends ConsoleProgram
{
    public void run()
    {
        int nffraction = readInt("What is the numerator of the first fraction?: ");
        int dffraction = readInt("What is the denominator of the first fraction?: ");
        int nsfraction = readInt("What is the numerator of the second fraction?: ");
        int dsfraction = readInt("What is the denominator of the second fraction?: ");
        int sum = 
        System.out.print(nffraction + "/" + dffraction + " + " + nsfraction + "/" + dsfraction + "=" + sum);
    }
}

This is the expected output "1/2 + 2/5 = 9/10" but i can't figure out the "= 9/10" part.

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
Joshua Wu
  • 9
  • 3
  • 3
    There are many, possibly 10s of 1000s of code snippets all across the internet with solutions to this problem. You simply need to google for it and pick the one that you are comfortable with. – Shankha057 Nov 07 '19 at 03:43
  • You either A) Create a method that has the ability to convert fractions directly to fractions or B) Convert the fractions to a double, and then convert it back. – FailingCoder Nov 07 '19 at 03:44

1 Answers1

1

To get the sum of two franctions a/b + c/d you need to do (a*d + c*b)/b*d.

So for your example:

int numerator = (nffraction * dsfraction + nsfraction * dffraction)
int denominator = dsfraction * dsfraction
System.out.print(nffraction + "/" + dffraction + " + " + 
nsfraction + "/" + dsfraction + "=" + numerator + "/" + denominator);

This wont reduce to the simplest form of the fraction though.

LockieR
  • 370
  • 6
  • 19