Jump to content

Help with Java fraction adding program?

Featured Replies

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;

 

}

}

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?

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;
}
}

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.