MATLAB程序设计与应用(第三版)刘卫国 答案(四)

第四章 MATLAB程序流程控制

一、选择题
1~5:BDCAC
6~10:ABADA
二、填空题
1.M文件。
2.1次。
3.while ;break。
4.function ;形式参数;形参;实际参数;实参。
5.局部变量;全局变量;global。
6.语法错误;程序逻辑错误;调试函数;调试工具。
三、应用题
1.s=108%奇数和
2.

if语句实现
a=input(‘a=’);
b=input(‘b=’);
c=input(‘c=’);
x=input(‘请输入x的值:’);
if x>=0.5 && x<1.5
y=ax^2+bx+c;
elseif x>=1.5 && x<3.5
y=(sin(b))^3+x;
elseif x>=3.5 && x<5.5
y=ln(abs(b+c/x));
else
disp(‘输入错误’);
end
switch语句实现
a=input(‘a=’);
b=input(‘b=’);
c=input(‘c=’);
x=0.5:0.01:5.5;
for i=1:length(x);%用循环求对应的x(i)取整和对应的y(i)
t=fix(x(i)-0.5);
switch(t) %switch来选择y(i)表达式
case 0
y(i)=ax(i)x(i)+bx(i)+c;
case {1,2}
y(i)=a
sin(b)^c+x(i);
case {3,4,5}
y(i)=log(abs(b+c/x(i)));
end
end
plot(x,y)

a=fix(rand(1,20)*100);%产生20个两位随机数
sum=0;
n=1;
for i=1:20
sum=sum+a(i);%求20个数的和
end
avg=sum/20;%求平均值
%求出小于平均值的偶数
for i=1:20
if (a(i)<avg)&&( rem((a(i)),2)==0 )
res(n)=a(i);
n=n+1;
end
end
res

for n = 1:20
nums= strcat(‘请输入20个数字中的第’,num2str(n),‘个数字:’);
numbers(n,1) = input(nums)
end
minimum = min(numbers)
maximum = max(numbers)

循环结构
sum1=0;
for n=1:63
y=2.^n;
sum1=sum1+y;
end
sum函数
n=1:63;
x=2.^n;
sum2=sum(x)

(1)
sum=0;
for n=1:100 %%这个地方的值分别改成100.1000.10000即可
s=(-1)^(n+1)/n;
if abs(s)>10^-6
sum=sum+s;
else
end
end
(2)
sum=0;
for n=1:100 %这个地方的值分别改成100.1000.10000即可
s=(-1)^(n-1)/(2n-1);
if abs(s)>10^-6
sum=sum+s;
else
end
end
(3)
sum=0;
for n=1:100 %%这个地方的值分别改成100.1000.10000即可
s=1/4.^n;
if abs(s)>10^-6
sum=sum+s;
else
end
end
(4)
sum=1;
for n=1:100 %%这个地方的值分别改成100.1000.10000即可
s=((2
n)(2n))/((2n-1)(2n+1));
sum=sum
s;
end

function fn=fib(n)
if ~isnumeric(n) || ~isreal(n) || n<0
error(‘输入的值必须为正整数’);
end
n=floor(n);
if (n<=2)
fn=1;
else
temp=[1,1];
for i=3:n
temp(i)=temp(i-1)+temp(i-2);
end
fn=temp(n);
end

函数文件
function [chenji,dianji] = ji(A,B)
chenji=A*B;
dianji=A.*B;
end
脚本文件的调用
a=1:5;
b=2:6;
[x,y]=ji(a,b’)
返回结果
x =
70
y =
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30

函数文件
function fn=sums(n,m)
fn=0;
for i=1:n
a=i.^m;
fn=fn+a;
end
调用求和结果
sums(100,1)+sums(50,2)+sums(10,-1)
ans =
4.7978e+04

x =
4 12 20
y =
2 4 6

若想要讲解可下方留言,看到就会回复!!!

  • 67
    点赞
  • 297
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值