我的"最低常见倍数"程序挂起,并没有输出答案

eth*_*nzh 2 python if-statement function lcm while-loop

我一直在努力学习编程,所以我一直在努力创建一个简单的程序,它将两个数字作为输入,并计算最低的公共倍数.我在Python中这样做是因为我不知道如何在Java中输入.现在发生的事情是,在我输入数字后程序就会挂起,没有任何反应.这里的任何指针将不胜感激.谢谢.

#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them

def lcmCalculator(one, two):
    """ takes two numbers as input, computes a number that evenly 
        divides both numbers """
    counter = 2 #this is the number that the program tried to divide each number by.
                #it increases by 1 if it doesn't divide evenly with both numbers.
    while True:
        if one % counter == 0 and two % counter == 0:
            print counter
            break
        else:
            counter += 1

print "\nThis program takes two numbers and computes the LCM of them...\n"

first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")

print lcmCalculator(first_number, second_number)
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 6

你的逻辑有点偏.这一行:

if one % counter == 0 and two % counter == 0:
Run Code Online (Sandbox Code Playgroud)

需要像这样重写:

if counter % one == 0 and counter % two == 0:
Run Code Online (Sandbox Code Playgroud)

此外,您的功能应该返回 counter而不是打印它.这有两个好处:

  1. 它将使脚本不会None在最后打印(函数的默认返回值).

  2. 它允许您压缩这两行:

    print counter
    break
    
    Run Code Online (Sandbox Code Playgroud)

    只有一个:

    return counter
    
    Run Code Online (Sandbox Code Playgroud)

最后,正如@FMc在评论中指出的那样,你可以通过做两件事来提高函数的效率:

  1. counter函数的两个参数中较小的一个开始.

  2. counter按此值递增.


以下是脚本的一个版本,它解决了所有这些问题:

#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them

def lcmCalculator(one, two):
    """ takes two numbers as input, computes a number that evenly 
        divides both numbers """
    counter = min_inp = min(one, two)
    while True:
        if counter % one == 0 and counter % two == 0:
            return counter
        else:
            counter += min_inp

print "\nThis program takes two numbers and computes the LCM of them...\n"

first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")

print lcmCalculator(first_number, second_number)
Run Code Online (Sandbox Code Playgroud)

哦,还有一件事. input在Python 2.x中,它将输入评估为真正的Python代码.意思是,使用不受控制的输入是危险的.

更好的方法是使用raw_input然后将输入显式转换为整数int:

first_number = int(raw_input("Enter your first number: "))
second_number = int(raw_input("Enter your second number: "))
Run Code Online (Sandbox Code Playgroud)