【问题标题】:Nested while loop not looping properly in python嵌套的while循环在python中没有正确循环
【发布时间】:2015-04-20 19:53:56
【问题描述】:

我是新手,我对我的 python 代码有疑问。它没有像我认为的那样执行。 搞砸的部分是嵌套的while:

import math
mu=4*math.pi*10**(-7)  ##mu naught
I=
float(input('Enter a value for the current measured in Amperes: '))
R=abs(float(input('Enter a value for the radius 
of the circle measured in meters: '))) ##radius
step=R/200  ##Step size for integration
B=[] ##array for B(r)
J=[]
Plot=[B,J]

k = 1 ##step counter for Circumfrence
j = 1 ##step counter for Radius
b_temp = 0 ##place holder to sum b(step*k)

D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
R_Vector = [R-j*step,0]

while(j*step<=R):
    while(k*step<=2*math.pi*R):
        r=(math.sqrt((R_Vector[0]-D_Vector[0])**2 + 
        (R_Vector[1]-D_Vector[1])**2))
        b_temp = b_temp + (mu/(4*math.pi))*I*step*step/(r**2)
        k=k+1
        D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
        R_Vector = [R-j*step,0]
        print(round(r,3), j)
    B.append(round(b_temp,8))
    print('New j value!')
    b_temp=0
    J.append(round(step*j,3))

    j=j+1

它应该减小半径(第一个 while 循环),然后围绕圆循环,将每块导线的磁场贡献相加。出于某种原因,它并没有像应有的那样在外部循环的每次迭代中循环内部循环,老实说,我不确定为什么。新的 j 值行是让我看看它是否循环正常,这是我的输出:

...
13.657 1
13.884 1
14.107 1
14.327 1
14.543 1
14.756 1
14.965 1
15.17 1
15.372 1
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
...

每个浮点数(半径值)末尾的 1 是 j 值,对于循环周围的每个圆圈,它都保持为 1...

【问题讨论】:

  • 我想我应该提到某些行被打断了,因为这些行太长而无法放入编辑框中。所以 I 和 R 输入实际上都是一条线,我想就是这样。
  • 期望的输出是什么?

标签: python loops while-loop


【解决方案1】:

您正在增加k,但从未将其重置为1。所以k * step 变得越来越大,直到内循环的条件变为假。此时很明显它不再被执行了。

请注意,当您只是在整数范围上进行迭代时,您应该避免使用while 循环。只需使用for j in range(a, b)。这完全避免了代码中的那种错误。

如果我没记错的话,您可以将循环替换为:

area = 2*math.pi*R

for j in range(1, R//step + 1):
    # j*step <= R holds
    for k in range(1, area // step + 1):
        # k * step <= area holds here

其中a // bab 的商。

【讨论】:

  • 感谢一百万,一行修复了它。
猜你喜欢
  • 2020-10-09
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
相关资源
最近更新 更多