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.
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.