10/09/2006

3.8 CONTINUE & RETURN

continue與break兩指令具有相同的功能,但break大部份都是跳到外圈,continue則只跳到對應之end後繼續執行,在巢狀if…end內,其功能大致相同。

將上例稍作修正,可以相互比較其功用之不同。本例仍然有使用break中斷執行while…end。所以兩者有不同的功能。


% Using continue to terminate the execttion.
n=1;
while 1
a=input('To proceed? (Y/N) ','s');
A=upper(a);
if isempty(A), A='Y';end
if A=='N', break; end
if A=='Y',
disp('OK, you know how to use CONTINUE, don''t you?')
disp('This statement uses CONTINUE to bypass the rest ones.')
disp(['You have tried ',int2str(n),' time(s)! Try it again.'])
n=n+1;
continue
end
disp('I don''t understand, please input again.')
end


>> show_continue
To proceed? (Y/N) y
OK, you know how to use CONTINUE, don't you?
This statement uses CONTINUE to bypass the rest ones.
You have tried 1 time(s)! Try it again.
To proceed? (Y/N) n

return也是中斷指令,但通常用於被呼叫之函數中,一旦遇到return指令,執行權將回到呼叫程式繼續執行。


function dd=show_det(A)
% Find the determinant of A
if isempty(A),
dd=1;
return
else
dd=det(A);
end


執行例:

>> d=show_det('')
d = 1
>> d=show_det([1 2 3;4 -5 6;7 2 1])
d = 188

沒有留言:

張貼留言