I need help using recursion in OOP: : A level 1 tree is a line. A level 2 tree is a line and two level 1 trees (it looks like: Y). A level 3 tree is a line and two level 2 trees. A level 4 tree is a line and two level 3 trees.
1 次查看(过去 30 天)
显示 更早的评论
I have a class set up with functions to drive forward and make turns. I just don't know how to make this work in a loop. The following is what the program should do for a n-level tree. If n is 0, do nothing. Otherwise, drive forward d, turn left a degrees, draw a level n-1 tree, turn right 2a degrees, draw a level n-1 tree, turn left a degrees, and drive backward d
回答(1 个)
Steven Lord
2016-10-14
Ah, LOGO and turtle graphics. That takes me back ... longer ago than I'd care to admit.
Is the code you posted in a function named tree or something similar? If it is, what input arguments does the function accept? If it is not in a function, you should create a function named tree. For this to be a recursive program, the tree function will have to call itself.
I would put each clause (a section ending in a period or a comma) in your instructions on how to draw the tree on a separate line of your file as a comment. Then after each of those comment lines, write a single command that does what the comment line says to do.
4 个评论
Steven Lord
2016-10-17
Almost. You've defined tree to have two inputs, obj and n. You're calling it in your recursive step with one input, just n-1. You should call it with two inputs, obj and n-1. Otherwise at the recursion step when you execute "if n <=0" the variable n won't exist and you'll receive an error.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!