【问题标题】:From Python to Java: Proper while loop declaration从 Python 到 Java:正确的 while 循环声明
【发布时间】:2013-08-05 21:31:09
【问题描述】:

如何用 Java 编写这段代码?

def gcd(a, b):
    """
    Calculate the Greatest Common Divisor of a and b.
    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

由于Type mismatch 错误,我似乎无法在Java 中执行while (b) {。看来我也不能完全在 Java 中完成 a, b = b, a%b 行。

【问题讨论】:

  • 为什么不买一本关于 Java 的书。这些是基础知识,您将在任何一本书的前几章中学习。
  • @RohitJain 有什么推荐的书吗?
  • 市场上有这么多。您可以从 Bruce Eckel 的 - Thinking in Java 开始。或者试试google.com
  • while b -> while (b != 0)a,b = b, a%b -> tmp = b; b=a%b;a=tmp.

标签: java python type-conversion greatest-common-divisor


【解决方案1】:
public static int gcd(int a, int b) {
        int temp;
        while(b != 0) {
            temp = a;
            a = b;
            b = temp % b;
        }
        return a;
}

Java 期望 while 的条件是布尔值,而不是 int

a, b = b, a%b 语法在 Java 中不起作用。您需要单独完成作业。

所以你可以设置a = b,然后设置b = a % b。我使用了一个临时变量来保存 a 的旧值,以便我可以计算 a % b(在我用 a = b 覆盖 a 之前)。

【讨论】:

    【解决方案2】:

    你真的需要一个while吗?它可以很简单-

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

    【讨论】:

    • 请注意,由于这段代码看起来更简单——因为它更短——它并不比使用“while”更有效。在没有为此优化的语言中,例如 lisp 或 scheme,函数调用将比交互式等效语言使用更多的系统资源。
    • @jsbueno Well..jh314 在我之前回答了这个问题。所以我想展示另一种方式,因为我已经在这里了。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多