Jump to content

Help with Java fraction adding program?


Equilibrium

Recommended Posts

Hello I'm a student in high school who is learning java, and I'm building a addition calculator for fractions. However it's not working and I can't figure out what my problem is. Can someone point out what is wrong in my program please?

 

Here is the program:

 

(n1=numerator of first fraction, d1=denominator of second fraction, and so on)

 

 

private static void Fraction(int n1, int d1, int n2, int d2){

 

int ntotal, wholenum=0;

int dnew1=0, dnew2=0;

if(d1!=d2){

dnew1=LCM(d1, d2);

dnew2=dnew1;

}

 

n1=n1*(dnew1/d1);

 

n2=n2*(dnew2/d2);

 

ntotal=n1+n2;

 

if(ntotal>=dnew1){

while(ntotal>=dnew1){

 

wholenum++;

 

ntotal=ntotal-dnew1;

 

}

}

Link to comment
Share on other sites

For one, use the code tags. There's a button that says 'insert code snippet, or just enclose the code in

[code]

and

[ / code ] 

(without the spaces) tags.

 

Unfortunately the forum software seems to like going completely bugnuts on the indentation unless you go for silly 8 space tabs, but it helps with readability regardless.

private static void Fraction(int n1, int d1, int n2, int d2){

int ntotal, wholenum=0;
int dnew1=0, dnew2=0;
if(d1!= d2){
   	dnew1 = LCM(d1, d2);
   	dnew2 = dnew1;
}

n1 = n1 * (dnew1/d1);

n2 = n2 * (dnew2/d2);

ntotal = n1 + n2;

if(ntotal >= dnew1) {
  	while(ntotal >= dnew1) {
  		wholenum++;
  		ntotal = ntotal - dnew1;
  	}
}

I can't see exactly what you're trying to do from here (some comments might help?), but I do see there's no closing parenthesis. This last step looks like it's for turning an improper fraction into a whole number + proper fraction. Perhaps you can explain what isn't working?

Link to comment
Share on other sites

It seems you are using numerator unifying & modular arithmetic, but I still have no idea ...

 

Your code fixed:

private static void Fraction (int n1, int d1, int n2, int d2)
{
int ntotal, wholenum=0;
int dnew1=0, dnew2=0;

if (d1 != d2)
{
	dnew1 = LCM(d1, d2);
	dnew2 = dnew1;
}
else dnew1 = dnew2 = d1;

n1 = n1 * (dnew1/d1);

n2 = n2 * (dnew2/d2);

ntotal = n1 + n2;

while (ntotal >= dnew1)
{
	wholenum++;
	ntotal = ntotal - dnew1;
}
}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.