gpt4 book ai didi

python - 我的 'lowest common multiple' 程序挂起,没有输出答案

转载 作者:行者123 更新时间:2023-11-28 20:23:16 25 4
gpt4 key购买 nike

我一直在尝试更多地参与编程,所以我一直在尝试制作一个简单的程序,将两个数字作为输入,并计算最小公倍数。我是用 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)

最佳答案

你的逻辑有点不对。这一行:

if one % counter == 0 and two % counter == 0:

需要这样改写:

if counter % one == 0 and counter % two == 0:

此外,您的函数应该返回 counter 而不是打印它。这有两个好处:

  1. 它会阻止脚本在最后打印None(函数的默认返回值)。

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

    print counter
    break

    变成一个:

    return counter

最后,正如@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)

哦,还有一件事。 Python 2.x 中的 input 将其输入计算为真正的 Python 代码。这意味着,使用不受控制的输入是危险的。

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

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

关于python - 我的 'lowest common multiple' 程序挂起,没有输出答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com