0
m = int(input("First number (0 to stop): "))
n = int(input("Second number: "))

def gcd(a, b):
   while b != 0:
        c = a % b
        a = b
        b = c
        if b == 0:
            break
   return a

print ("The greatest common divisor of", n,"and", m, "is", abs(gcd(m,n)))

当 m 等于 0 时,如何跳出这个 while 循环。

4

1 回答 1

2

根据您的输入提示,您可能需要一个外部循环(0 to stop)

def gcd(a, b):
   while b != 0:
        c = a % b
        a, b = b, c  # tuple assignment FTW!
        if b == 0:
            break
   return a

while True:
    m = int(input("First number (0 to stop): "))
    if m == 0:
        break
    n = int(input("Second number: "))
    print("The greatest common divisor of {0} and {1} is {2}".format(n, m, abs(gcd(m, n))))
于 2012-10-21T06:06:42.390 回答