这是基于文本的Python实现,该算法用于使用 REPEAT ... UNTIL 循环来计算数字是否为质数。 每当我尝试运行它时,它不会输出任何内容。 有人可以告诉我这段代码有什么问题吗? 仅供参考,我是新手。预先谢谢你!
prime = True
number = int(input("Enter a number : "))
counter = 2
while True:
modulus = number % counter
if modulus == 0:
prime == False
counter = counter + 1
#The loop for until statement
if counter == number-1 or prime == False:
break
if prime == True:
print("Prime : ", number)
else:
print("Not prime : ", number)
答案 0 :(得分:1)
我不确定为什么不输出任何东西,但是行prime == False
是错误的,应该是
prime = False
答案 1 :(得分:0)
prime = True
number = int(input("Enter a number : "))
counter = 2
while True:
modulus = number % counter
if modulus == 0:
prime == False
counter = counter + 1
#The loop for until statement
if counter == number-1 or prime == False:
break
if prime == True:
print("Prime : ", number)
else:
print("Not prime : ", number)`
如第10行所示,素数= False不是素数== False
答案 2 :(得分:0)
给这个版本一个机会。
主要问题是:
prime == False
循环下的if
语句被设置为布尔表达式,而不是变量赋值。while
循环以运行while prime == True
。这样,循环将在检测到输入数字与素数指定之间出现第一种矛盾的时刻时中断prime = True
number = int(input("Enter a number : "))
counter = 2
while prime == True:
modulus = number % counter
if modulus == 0:
prime = False
counter = counter + 1
if counter == number-1 or prime == False:
break
if prime == True:
print("Prime : ", number)
else:
print("Not prime : ", number)