如何使用龟图形在python中找到圆的直径

时间:2017-11-11 16:57:51

标签: python

我无法弄清楚如何计算圆内点的坐标。现在我的程序应该计算方形内圆圈内的点,并将其除以总点数。

import turtle
import random


t=turtle.Turtle()
insideCircleCount = 0



def square():
   for y in range(4):
      t.forward(200)
      t.left(90)


def circle():
    t.penup()
    t.setpos(100,0)
    t.pendown()
    t.circle(100)


def randomDot():
    z=int(input("iterations:"))
    for y in range(z):
        t.penup()
        t.pensize(1)
        x=random.randint(0,200)
        y=random.randint(0,200)
        t.goto(x,y)
        t.pendown()
        t.dot()
        insideCircle(x,y)


def insideCircle(x,y):
    if ((x*x + y*y)<100):
        insideCircleCount+=1



#main
square()
circle()
randomDot()
print('Dots inside circle account for ', insideCircleCount)

1 个答案:

答案 0 :(得分:0)

import turtle
import random

t=turtle.Turtle()
insideCircleCount = 0

def square():
    for y in range(4):
        t.forward(200)
        t.left(90)

def circle():
    t.penup()
    t.setpos(100,0)
    t.pendown()
    t.circle(100)

def randomDot():
    z=int(input("iterations:"))
    for y in range(z):
        t.penup()
        t.pensize(1)
        x=random.randint(0,200)
        y=random.randint(0,200)
        t.goto(x,y)
        t.pendown()
        t.dot()
        insideCircle(x,y)

def insideCircle(x,y):
    # Here the circle has a offset with center at (100,100)
    #(x – h)^2 + (y – k)^2 = r2
    if (((x-100)**2 + (y-100)**2) < 100**2):
        # you were trying to access a local variable before assignment
        #this fixes that
        global insideCircleCount
        insideCircleCount+=1

#main
square()
circle()
randomDot()
print('Dots inside circle account for ', insideCircleCount)
turtle.mainloop() #stops the window from closing