迎 eg4.用for循环求阶乘 n fac=1 n fac=1; n fac= 2 n=5; n fac= 6 for i=1:n n fac= 24 n_fac=n fac*i n fac= 120 end eg5.用for循环求平方、平方根、立方根 for ii=1:10 Square(ii)=ii^2 Square_root(ii)=ii(1/2) cute_root(ii)=ii(1/3) end 6
6 eg4. 用for循环求阶乘 n_fac=1; n=5; for i=1:n n_fac=n_fac*i end eg5. 用for循环求平方、平方根、立方根 for ii=1:10 Square(ii)=ii^2 Square_root(ii)=ii^(1/2) cute_root(ii)=ii^(1/3) end n_fac = 1 n_fac = 2 n_fac = 6 n_fac = 24 n_fac = 120
迎 eg. 2.while循环 i=1 while i<10 while expression a(i)=i a=123456789] statementl i=i+l statement2 C=10 end c=i end eg:使用while循环计算f)=siny,x<5且每次x递增 In(x). x=0.1; f= while x<5 -4.0651e+002-1.5921e+003i f=sin(x) X= x=x+l0g(x) 5.5640+9.2717i end 7
7 2. while循环 while expression statement1 statement2 …… end eg: 使用while循环计算f(x)=sin(x) ,x<5且每次 x递增 ln(x) 。 x=0.1; while x<5 f=sin(x) x=x+log(x) end f = -4.0651e+002 -1.5921e+003i x = 5.5640 + 9.2717i eg. i=1 while i<10 a(i)=i i=i+1 end c=i a=[1 2 3 4 5 6 7 8 9] C=10
迎 2.3.2条件语句 条件语句的分支结构形式一般为: if control expr_1 statementl statement2 blockl elseif control expr_2 statementl statement2 block2 nn■。■■■n else statementl statement2 block3 end 8
8 statement1 statement2 block1 ………… elseif control_expr_2 statement1 statement2 block3 …………. end statement1 statement2 block2 ………… else 2.3.2 条件语句 if条件语句的分支结构形式一般为: if control_expr_1
② eg.对于方程,ax2+bx+c=0求其二次方根。 已知r= -b±Vb2-4ac 2a 则程序如下: if(b2-4*a*c)<0 msg(“此方程有两复数根”) elseif (b2-4*a*c)==0 msg(“此方程有两恒等的实数根) else msg(“此方程有两不等的实数根) end 9
9 eg. 对于方程, 求其二次方根。 已知 则程序如下: if (b^2-4*a*c)<0 msg(“此方程有两复数根”) elseif (b^2-4*a*c)==0 msg(“此方程有两恒等的实数根”) else msg(“此方程有两不等的实数根”) end a b b ac x 2 4 2 − ± − = 0 2 ax + bx + c =
迎 嵌套的语句结构 ■嵌套的f语句:多个f语句合在一起 ■ifx>0 ■ ◆ if y<0 end end 10
10 嵌套的if语句结构 嵌套的if 语句:多个if 语句合在一起 if x > 0 … if y < 0 … end … end