【问题标题】:i need help converting this program into a while loop from for loop with python 2.7我需要帮助将这个程序从 for 循环与 python 2.7 转换为 while 循环
【发布时间】:2018-09-25 13:54:39
【问题描述】:

将此for循环转换为while循环查找pi

import turtle
import math
import random

t = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(-400,-400,400,400)

t.pu()
t.speed(0)
t.goto(0,-400)
t.pd()
t.color("green")
t.circle(400)
t.color("red")
hits=0.0
numdarts = 100
for i in range(numdarts):
    randx = random.uniform(-1,1)
    randy = random.uniform(-1,1)
    if (randx**2+ randy**2)<1:
        hits+=1.0

    t.pu()
    t.goto(400*randx,400*randy)
    t.pd()
    t.dot()
print 4*(hits/numdarts)
wn.exitonclick()

考虑到近似值可接受的误差量,想要使用 while 循环来估计 pi ​​的值

【问题讨论】:

  • 是什么阻止你这样做?

标签: python python-2.7 loops for-loop while-loop


【解决方案1】:

您只需要检查 numdarts 是否比 0 和倒计时 numdarts。 像这样:

numdarts =100
while numdarts > 0:
     numdarts-=1
     [rest of Loop]

虽然我不明白,为什么你应该在这个特殊的用例中这样做,因为你可能会遇到一个无限循环。

【讨论】:

    【解决方案2】:

    将此for 循环转换为while 循环:

    i = 0
    while True:
        #your code
        i += 1
        if i == numdarts:
            break
    

    这基本上保持从 0 到 99 的循环,与范围 (100) 相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2019-06-07
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 2018-02-22
      相关资源
      最近更新 更多