【问题标题】:Working with calculating GCD - Python function return使用计算 GCD - Python 函数返回
【发布时间】:2016-12-05 12:08:31
【问题描述】:

我写了一个计算两个数字的 GCD 的代码。 (24,12) 的 gcd 是 12。函数compute_gcd 计算 GCD 并返回它,它会打印在主函数中。但是,当我将其返回到主函数时,输出为none,而当我在compute_gcd 函数本身中打印它时,输出为12。

退回 GCD 时我哪里出错了?

def compute_gcd(a,b):
    if(b==0):
        return a             # Prints 12 if I replace with print a
    else:
        compute_gcd(b,a%b)

def main():
    a=24
    b=12 
    print compute_gcd(a,b)   # Prints none

main()

【问题讨论】:

标签: python python-2.7 return return-value greatest-common-divisor


【解决方案1】:

您忘记在else 分支中添加return。这有效:

def compute_gcd(a,b):
    if b == 0:
        return a
    else:
        return compute_gcd(b,a%b)

def main():
    a=24
    b=12

    print compute_gcd(a,b)   # Prints 12

main()

【讨论】:

    【解决方案2】:

    试试这个...你必须在else 语句中添加一个return

    def compute_gcd(a,b):
        if(b==0):
            return a
        else:
            return compute_gcd(b,a%b)
    
    def main():
        a = 24
        b = 12
    
        print(compute_gcd(a,b))
    
    main()
    

    【讨论】:

      【解决方案3】:

      您的 else 条件没有返回,因此输出为无。如果您将其更改为

      else:
        return compute_gcd(b,a%b)
      

      你会得到12

      【讨论】:

      • 这与 13 分钟前发布的答案有何不同?
      • 我没有看到它,因为答案选项卡已打开。否决票,是的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多