2014-02-16 78 views
0

任何人都可以給我提示,我可以如何使用Matlab內置菜單功能來計算面積,例如圓柱體,週期和矩形,而無需在腳本中打印菜單選項?謝謝。MATLAB內置菜單功能

例如下面的腳本計算面積,但打印出來的菜單選項

%areaMenu 
%this script asks the user for a type of area 
%and prints the area using if-else 
%units are assumed to be inches 
%display a menu 
disp('Menu'); 
disp('1. Cylinder'); 
disp('2. Circle'); 
disp('3. Rectangle'); 
%choice selection 
i=input('Please select your choice now: '); 
if i==1 
    disp('well! your choice is cylinder'); 
r=input('enter radius: '); 
%error check 
if (r<=0) 
    disp('Error! Please enter a positive number') 
    r=input('enter radius again: '); 
end 
l=input('enter length: '); 
%error check 
if l<=0 
    disp('Error! Please enter a positive number') 
    l=input('enter length again: '); 
end 
%area calculated and print 
%assume the cylinder is closed both sides 
area=2*pi*r*r+2*pi*r*l; 
fprintf('The area is %.2f\n',area); 
elseif i==2 
    disp('well! your choice is cycle') 
r=input('enter radius: '); 
%error check 
if (r<=0) 
    disp('Error! Please enter a positive number') 
    r=input('enter radius again: '); 
end 
%area calculated and print 
area=pi*r*r; 
fprintf('The area is %.2f\n',area); 
elseif i==3 
    disp('well! your choice is rectangle') 
l=input('enter length: '); 
%error check 
if l<=0 
    disp('Error! Please enter a positive number') 
    l=input('enter length again: '); 
end 
w=input('enter width: '); 
%error check 
if w<=0 
    disp('Error! Please enter a positive number') 
    w=input('enter width again: '); 
end 
%area calculated and print 
area=l*w; 
fprintf('The area is %.2f\n',area); 
else 
fprintf('invalid choice! Enter a valid choice next time'); 
end 
end 
+1

請對你的問題更具體。你認爲什麼是菜單功能? – fuesika

+0

您是否嘗試查看['menu']的文檔(http://www.mathworks.co.uk/help/matlab/ref/menu.html)? – Notlikethat

+0

@pyStarter:我現在嘗試編輯帖子 – joke

回答

0

使用內置功能如更換這樣簡單:

disp('Menu'); 
disp('1. Cylinder'); 
disp('2. Circle'); 
disp('3. Rectangle'); 
%choice selection 
i=input('Please select your choice now: '); 

與此:

i = menu('Choose shape', 'Cylinder', 'Circle', 'Rectangle'); 

或者,使用單元陣列:

shapes = {'Cylinder', 'Circle', 'Rectangle'}; 
i = menu('Choose shape', shapes); 

此外,menu確保選擇了一個有效的號碼,因此您不再需要在您的代碼中檢查。