필터 지우기
필터 지우기

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
Kyle Reagan
Kyle Reagan 2016년 10월 14일
t = Turtle(); a = 40; b = 4; while n > 0
t = t.fd(b);
t = t.lt(a);
t = t.fd(b);
t = t.bk(b);
t = t.rt(2*a);
t = t.fd(b);
t = t.bk(b);
t = t.lt(a);
t = t.bk(b);
end
This is what I have so far.

댓글을 달려면 로그인하십시오.

답변 (1개)

Steven Lord
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
Kyle Reagan
Kyle Reagan 2016년 10월 17일
Now I have it so that my input is n and my output is y.
obj = Turtle(); function [y] = tree(obj,n) % Creates tree to the order n t = Turtle(); a = 60; % angle in degrees d = 4; % distance turtle travels
% If n is 0, if n <= 0 % do nothing. t = t.fd(0); % Otherwise, else % drive forward d, t = t.fd(d); % turn left a degrees, t = t.lt(a); % draw a level n-1 tree, y = tree(n-1) % turn right 2a degrees, t = t.rt(2*a); % draw a level n-1 tree, y = tree(n-1) % turn left a degrees, t = t.lt(a); % and drive backward d t = t.bk(d); end end
Steven Lord
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 CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by