matlab实验三答案详解
实验三 选择结构程序设计
实验内容
程序代码
function f(x)
if x<0&x~=-3
y=x*x+x-6;
elseif x>0&x<5&x~=2&x~=3
y=x*x-5.*x+6;
else
y=x*x-x-1
end
y
运行结果
>> f(-7)
y =
36
>> f(2.5)
y =
-0.2500
>> f(90)
y =
8009
程序代码
score=input('分数=');
if score<=100&score>=0
switch fix(score/10)
case{9,10}
grade='A';
case{8}
grade='B';
case{7}
grade='C';
case{6}
grade='D';
otherwise
grade='E';
end
grade
else
disp('输入有误,请输入正确的百分制成绩');
end
运行结果
>> 分数=56
grade =
E
>> f
分数=345
输入有误,请输入正确的百分制成绩
程序代码
time=input('工作时间=');
switch time
case{time>120}
wage=(time-120)*(1+15/100)*84+120*84;
case{time<60}
wage=time*84-700;
otherwise
wage=time*84
end
运行结果
>> f
工作时间=150
wage =
12600
>> f
工作时间=50
wage =
4200
>> f
工作时间=110
wage =
9240
程序代码
A=10+90*rand(5);
a=fix(A(3,3))
b=fix(A(2,4))
x=input('输入一个运算符号','s');
switch x
case {'+'}
c=a+b;
case{'-'}
c=a-b;
case{'*'}
c=a*b;
case{'/'}
c=a/b;
otherwise
c='无效'
end
c
运行结果
>> f
a =
55
b =
59
输入一个运算符号+
c =
114
>> f
a =
77
b =
14
输入一个运算符号/
c =
5.5000
>> f
a =
30
b =
58
输入一个运算符号#
c =
无效
c =
无效
程序代码
A=input('输入一个5行6列的矩阵A=');
n=input('输入一个正整数n=');
if n<5&n>0
disp(A(n,:));
else
disp(A(5,:));
end
lasterr
运行结果
>> f
输入一个5行6列的矩阵A=[1 2 3 4 5 5;2 3 4 5 7 6;2 9 2 2 2 3;11 2 11 9 7 3;2 3 4 5 6 7]
输入一个正整数n=6
2 3 4 5 6 7
ans =
Undefined function or variable 'clcl'.
>> f
输入一个5行6列的矩阵A=[1 2 3 4 5 5;2 3 4 5 7 6;2 2 2 2 2 3;11 2 3 9 7 3;2 3 4 5 6 7]
输入一个正整数n=3
2 2 2 2 2 3
ans =
Undefined function or variable 'clcl'.