最高的刻度是半英寸标记,接下来的两个最高刻度是四分之一英寸标记,甚至更短的标记用于标记八分之一和十六分之一,很快。编写以下递归函数:drawRuler(x,y,width,height)
$import turtle
'''
def height(range(4)):
for i in
'''
Runs = 10
def drawRuler(x,y,width,height):
if Runs == 0:
print("End.")
else:
#turtle.goto(x,y)
turtle.forward(width)
turtle.left(90)
turtle.forward(height)
turtle.right(180)
turtle.forward(height)
turtle.left(90)
drawRuler(0,0,width,height/4)
drawRuler(-50,0,15,100)
drawRuler(0,0,15,50)
Runs == Runs - 1
drawRuler(0,0,15,100)
$
我的问题是如何让它创造不同的高度,并在标尺后面创建相同的高度。我觉得我的功能很接近,但到目前为止。
答案 0 :(得分:0)
递归背后的想法是使用一个函数将问题分解成越来越小的块,直到块不再被分割为止。
在上面的标尺示例中,您可以这样想......
最小的块将是标尺中最小的分区。在你的情况下,它的1/16"。 然后,您需要递归调用您的函数,直到它将标尺分成1/16"的块。一旦调用drawRuler()的length参数是1/16英寸,问题就很简单了。你只需画出正确的长度刻度线。您可以通过根据函数调用中的length参数决定如何绘制刻度线来实现。如果长度为1/16,则绘制1/16刻度。如果长度为1/2英寸,则绘制1/2英寸刻度等等......
调用堆栈看起来像这样......
drawRuler(0, 0, 10, 1) // draw a ruler at 0,0 with a length of 10 and a width of 1
drawRuler(0, 0, 5, 1) // draw the first half of the 10" ruler starting at 0
drawRuler(2.5, 0, 2.5, 1) // draw the first half of the 5" ruler starting at 0
// keep dividing the ruler until you reach the 1/16 size
// once you reach the one sixteenth size, draw the correct size tick mark for passed in length
drawRuler(2.5, 0, 2.5, 1) // draw the second half of the 5" ruler starting at 2.5
// same as above
drawRuler(5, 0, 5, 1) // draw the second half of the 10" ruler starting at 10
// same as above
该功能看起来像这样......
drawRuler(x, y, length, width)
{
if (length > 1/16) then
drawRuler(x, y, length / 2, width) // draw the left side
drawRuler(x + (width * 1/2), y, length / 2, width) // draw the right side
end if;
// draw the tick mark here using Turtle Graphics. The length of the tick mark
// is based on the length parameter pass into the function.
// For example,
// if the length is 10 or any even inch mark the length would be very long
// if the length is 5.5 or any 1/2 inch value the length would be long
// if the length is 2.25 or any 1/4 inch value the length would be medium
// if the length is 0.125 or any 1/8 inch value the length would be medium-short
// if the length is 0.0625 or any 1/16 inch value then the length would be short
}