gpt4 book ai didi

python - 如何将 C++ for 循环转换为 Python?

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:48 25 4
gpt4 key购买 nike

我用 C++ 写了一段代码,想把它转换成 Python3。如何做到这一点?

int N = 1000
for (p=2; p*p<=N; p++)
for (w=p*p; w<=N; w=w+p)

我试图将第一个 for 循环更改为:

for p in range(2,N**0.5+1):

但它不起作用 - TypeError: 'float' object cannot be interpreted as an integer

那么第二个 for 循环呢?

最佳答案

试试这个(在 python 中你应该用 while 来做):

N = 1000
p = 2

while p*p <= N:

p = p + 1
w = p*p
print(p)

while w <= N:
w = w + p
print(w)

<罢工>

更新:

出现错误“TypeError: 'float' object cannot be interpreted as an integer”的原因是“range”函数需要“integers”作为参数,而“N ** 0.5”是 float 类型, “N ** 0.5+1”也是如此。要解决此问题,您可以简单地使用“int”函数将 float 转换为整数。以下代码就是您要查找的内容:

N = 1000
for p in range(2, int(N ** 0.5) + 1, 1):
for w in range(p * p, N + 1, p):
print(p, w)

关于python - 如何将 C++ for 循环转换为 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47311352/

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