我的程序的一部分根据用户输入显示n个素数,但无论我输入什么,它只打印“1”
def listPrimeNumbers():
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
print("\n"*10)
for i in range(1, amountOfNumbers):
prime = True
for i in range(2,i):
if (num%i==0):
prime = False
if prime:
print(i)
print("\n"*10)
print("Type '0' to try again and '1' to go to the main menu")
print("\n"*10)
choice = int(input("Choice ---> "))
if choice == 0:
print("\n"*100)
listPrimeNumbers()
elif choice == 1:
print("\n"*100)
main()
答案 0 :(得分:1)
更改您的' for'循环到这个:
for num in range(1, amountOfNumbers):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print(num)
num并未在代码中的任何位置定义,我认为这就是您的意思。
你是如何调用代码的?就是这样,我无法运行它。我设法通过在底部添加对函数listPrimeNumbers()的调用来运行它。
无论如何,假设您发布的代码是您的整个代码,这是适用于我的版本:
import sys
def listPrimeNumbers():
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
print("\n"*10)
for num in range(1, amountOfNumbers):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print(num)
print("\n"*10)
print("Type '0' to try again and '1' to go to the main menu")
print("\n"*10)
choice = int(input("Choice ---> "))
if choice == 0:
print("\n"*100)
listPrimeNumbers()
elif choice == 1:
print("\n"*100)
print 'Bye'
sys.exit(0)
listPrimeNumbers()
答案 1 :(得分:0)
如果我正确理解了这个问题,那么代码中就存在一个逻辑缺陷,因为即使修改了Alex建议(哪个有效),你只需打印所有数字,这些数字都是用户输入的值而不是,似乎是问题,用户输入的数量。
例如,根据你的问题,如果用户输入10,我明白你应该打印前10个素数(1,2,3,5,7,11,13,17,19,23)而不是素数高达10(1,2,3,5,7)
如果我的假设是正确的,那么代码应该是这样的:
import math
def listPrimeNumbers(n):
l = int(math.sqrt(n))+1
if n == 1:
return True
for x in range(2, l):
if (n%x==0):
return False
return True
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
counter = 0
n = 0
while (counter < amountOfNumbers):
n += 1
if listPrimeNumbers(n) == True:
counter += 1
print(n)
我省略了重复该过程的部分,所以你需要重新运行该程序再试一次