递归背后的想法是使用函数将问题分解成越来越小的块,直到无法再分割。
在上面的标尺示例中,您可以这样想...
最小的块将是标尺中最小的分区。在你的情况下,它是 1/16"。
然后,您需要递归调用您的函数,直到它将标尺分成 1/16" 的块。一旦调用 drawRuler() 中的长度参数为 1/16 英寸,问题就很简单了。您只需必须绘制正确的长度刻度线。您可以通过根据函数调用中的长度参数决定如何绘制刻度线来做到这一点。如果长度为 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
}