I'm writing a program that lets the user enter a nominator and a denominator, which the program then converts to mixed form (9/8 -> 1 1/8 and so on). It works just fine, except for when the denominator is greater than the nominator. When I started debugging the code, I found something I couldn't understand. Below is the method fraction, which at the end of it calls the method gcd (greatest common divider) to determine what to divide the remainder of the integer division and the denominator with.
public static int[] fraction(int nominator, int denominator) //Rewrites a fraction to mixed form
{
//nominator == 7 and denominator == 8
int[] result = {0, 0, 0};
int quotient;
int remainder;
if (denominator == 0)
return null;
if (nominator == 0)
{
result[0] = 0;
result[1] = 0;
result[2] = 0;
return result;
}
kvot = nominator/denominator;
rest = nominator % denominator;
result[0] = quotient;
result[1] = remainder/(gcd(remainder, denominator)); //According to the debugger, the values are still 7 and 8 here
result[2] = denominator/(gcd(remainder, denominator));
return result;
}
When called with the above values, something seems to go wrong, because the values the second method recieves from the first is wrong. Instead of 7 and 8, it receives 7 and 1. Is the error in the code provided, or does it seem to be somewhere else?
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{ //The debugger tells me that a == 7 and b == 1, even though the method was called with 7 and 8
int temp, c;
if (b == 0)
{
System.out.println("Nominator is 0, error");;
}
if (b > a)
{
temp = b;
b = a;
a = temp;
}
c = a % b;
a = b;
b = c;
return a;
}