我想编写一个程序,用于在 python 中打印 3n+2 级数的前 x 项,它们不是 4 的倍数。为此,我使用 while 循环编写了一段代码,并且运行良好。然后我再次使用 for 循环编写了相同的代码,但它没有给出正确的答案。
x = int(input())
n = 1
count = 1
while count < x:
temp = 3*n + 2
if temp % 4 != 0:
print(temp, end=" ")
count += 1
n += 1
for count in range(x+1):
temp = 3*n + 2
if temp % 4 != 0:
print(temp, end=" ")
else:
count -= 1
n += 1
上面是 while 循环和 for 循环中的代码,但 for 循环代码给出了错误的答案(基本上并不是所有术语都会打印更高的数字,如 x=5 或以上)。
我希望第二个代码(for 循环)得到与第一个代码(while 循环)相同的输出
第二个代码(使用 for 循环)中的问题是,当 temp % 4 == 0 时,您在 else 块中将计数重置为 0。这导致循环跳过某些项的计数。
x = int(input())
count = 0
for n in range(1, x+1):
temp = 3*n + 2
if temp % 4 != 0:
print(temp, end=" ")
count += 1
if count == x:
break
我想我明白了,但也可能不明白。你可以尝试一下吗?