模块化程序:一个问题分解成几个模块。
如果函数中有子函数的话每个函数末尾写end来结束该函数。
程序:
choice=eoption;
while choice~=4
switch choice
case 1
explation;
case 2
limite;
case 3
x=input('please the value for x:');
expfn(x);
end
choice=eoption;
end
function choice=eoption
%用户必须从菜单里面选择一项 不能点击菜单窗口右上角的关闭
%print the menu of option and error-check
%until the user pushes one of the buttons
choice=menu('choose an option','explanation','limnit','exponantioal funtion','exit program');
while choice==0
disp('error--please choose an button');
choice=menu('choose an option','explanation','limnit','exponantioal funtion','exit program');
end
function limite
n=askforn;
fprintf('an approximation of e with n=% d is % .2f \n',n,(1+1/n)^n)
end
function outn=askforn
inputn=input('enter the postive integfer for n:')
num2=int32(inputn);
while num2 ~=inputn||num2<0
inputn=input('enter the postive integfer for n:')
num2=int32(inputn);
end
outn=inputn; %注意此处不能写成outn=num2貌似int32截取会出现问题
end
function expfn(x)
fprintf('valuse of exp(x) is %.2f \n',exp(x));
n=10
fprintf('approximate exp(x) is %.2f \n',appex(x,n));
end
function out=appex(x,n)
outval=1;
runprod=1;
for i=1:n
runprod=runprod*i;
outval=x^i/runprod+outval;
end
out=outval;
end
持续变量:
用persistent来声明 例如persistent count;那么count就是一个持续变量了。