Java 为什么我的方法不使用正确的值调用我的另一个方法?
我正在编写一个程序,允许用户输入一个命名符和一个分母,然后程序将其转换为混合形式9/8->1 1/8,依此类推。除了分母大于提名者外,它工作得很好。当我开始调试代码时,我发现了一些我无法理解的东西。下面是方法分数,它在结尾调用方法gcd最大公除法,以确定整数除法的剩余部分和分母的除法Java 为什么我的方法不使用正确的值调用我的另一个方法?,java,methods,Java,Methods,我正在编写一个程序,允许用户输入一个命名符和一个分母,然后程序将其转换为混合形式9/8->1 1/8,依此类推。除了分母大于提名者外,它工作得很好。当我开始调试代码时,我发现了一些我无法理解的东西。下面是方法分数,它在结尾调用方法gcd最大公除法,以确定整数除法的剩余部分和分母的除法 public static int[] fraction(int nominator, int denominator) //Rewrites a fraction to mixed form {
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;
}
当使用上述值调用时,似乎出现了问题,因为第二个方法从第一个方法接收到的值是错误的。它接收的不是7和8,而是7和1。是代码中提供的错误,还是它似乎在其他地方
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;
}
您的gcd功能不正常。如果你使用欧几里德算法,你可以这样计算gcd
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{
if (b == 0) {
return a;
} else {
return gcd(b, a%b);
}
}
您也可以使用其他解决方案,但建议的方法不合适。什么是sgd方法?请出示gcdOh抱歉,我在发帖前将所有内容重命名为英语,我只是忘记了那个。gcd和sgd是一样的,我现在编辑它了。你也忘了使用递归方法吗?您使用的GCD算法看起来像一个递归算法,但它缺少一个基本情况,应该返回gcda,bc=a%b;a=b;b=c;返回一个;?你知道这些只是局部变量,所以这不会影响你调用它们的变量的值吗?这完全等同于返回b;。我不确定我是否理解你的意思,这个方法应该只返回一个int,这是用来调用这个方法的两个整数的gcd