【问题标题】:Why do I get the answer 1 only to program to find divisor?为什么我得到答案 1 只是为了编程找到除数?
【发布时间】:2022-01-15 14:08:34
【问题描述】:

这是求两个数的除数的程序,但我输入的任何数的答案都是 1。我哪里错了?

def divisor(a,b):
    result=1
    for i in range(b,-1):
        if a%i==0 and b%i==0:
            result=i
            break

    return result

num=input("calculate HCF of: ").split(",")
print(divisor(int(num[0]),int(num[1])))

【问题讨论】:

  • 无法复制。当我输入6,9 运行此代码时,我得到3 的输出。
  • 没问题,可能是你输入的测试值有问题,可以试试28, 8。
  • 不确定,您可能在拆分输入后得到字符串。将它们转换为数字,然后再次检查。希望它能解决你的问题
  • 这是一种首先计算值的低效方法。请改用Euclid's algorithm。
  • 最好从 a 和 b 中的较小者开始 for 循环,而不是总是使用 b。

标签: python function variables input output


【解决方案1】:

试试这个:

for i in range(1, min(a, b)+1):
    result = 0
    if a%i==b%i==0:
        result+=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多