2014-03-05 86 views
-2
private static int setGCD() 
    { 
    int a, b; 

    gCD(a,0) = a; //here -the left-hand side of the assignment must be a variable// 
    gCD(a,b) = gCD(b,a%b); //here -the left-hand side of the assignment must be a variable// 
    finalNumer = enterNumer/gCD; //here -cannot make static reference to finalNumer, enterNumer, or gCD// 
    finalDenom = enterDenom/gCD;//here -cannot make static reference to finalDenom, enterDenom, gCD 
    } 

此方法的目的是找到用户在上述编程中输入的分子和分母的最大公分母(GCD)。但我一直在说错误(在评论中),这让我感到困惑,因为这是我的老师在董事会上写的,但这对我来说绝对没有意义!请帮忙!作业的左侧必须是变量

+0

通过上面的编程我的意思是编程没有在这里显示 – NeverWalkAlone

+0

其中是在setGCD方法中调用的方法? – Kick

+2

翻转:'a = gCD(a,0);' –

回答

0

存在用于Euclidean algorithm 2个实施方式:

  • 迭代(伪码)
function gcd(a, b) 
    while a ≠ b 
     if a > b 
      a := a − b 
     else 
      b := b − a 
    return a 
  • 递归(伪码)
function gcd(a, b) 
    if b = 0 
     return a 
    else 
     return gcd(b, a mod b) 

我相信你想后者的基础上,你所写的内容:

public static int gcd(int a, int b) { 
    if (b == 0) 
     return a; 
    else 
     return gcd(b, a % b); 
} 

很容易转成伪代码的Java正确。

+0

非常感谢! – NeverWalkAlone

+0

您的教授/书籍/导师是否将GCD算法称为欧几里德算法? –

0

这个函数返回你在找什么,那么你可以使用它的输出设置GCD你喜欢的地方:

public static int gcd(int a, int b) 
{ 
    while (a != b) 
    { 
     if (a > b) 
     { 
      a = a - b; 
     } 
     else 
     { 
      b = b - a; 
     } 
    } 
    return a; 
} 

参见Euclidean Algorithm维基文章。

+0

除了这不是老师给他的学生的算法... – Alnitak