1.输入长方形的长和宽,计算长方形的周长和面积并输出
len=input('input the length of rectangle:');
w=input('input the width of rectangle:');
girth=len*2.0+w*2.0;
area=len*w;
fprintf('girth=%f,area=%f\n',girth,area);
2.输入三角形的三条边(要满足构成三角形的条件),求三角形的周长和面积
解题关键:海伦公式求面积
edge1=input('input the first edge of triangle:');
edge2=input('input the second edge of triangle:');
edge3=input('input the thrid edge of triangle:');
if(edge1+edge2>edge3 && edge2+edge3>edge1 && edge1+edge3>edge2)
girth=edge1+edge2+edge3;
tmp=girth/2;
area=(tmp*(tmp-edge1)*(tmp-edge2)*(tmp-edge3))^(0.5);
fprintf('girth=%f,area=%f\n',girth,area);
else
fprintf('error:The edge is illegal.');
end
3.输入一元二次方程的三个系数,求一元二次方程的根。
解题关键:公式法求一元二次方程的根。
a=input('input the a of ax^2+bx+c=0(not equal to 0):');
b=input('input the b of ax^2+bx+c=0:');
c=input('input the c of ax^2+bx+c=0:');
tmp=b^2-4*a*c;
if a==0
fprintf('error:illegal value of a.\n');
else if tmp<0
x1=(-b)/(2*a);
x2=((-tmp)^0.5)/(2*a);
fprintf('Δ<0 x1=%f,x2=%f\n',x1,x2);
end
if tmp==0
x1=(-b)/(2*a);
fprintf('Δ=0 x1=x2=%f\n',x1);
end
if tmp>0
x1=(-b+tmp^0.5)/(2*a);
x2=(-b-tmp^0.5)/(2*a);
fprintf('Δ>0 x1=%f,x2=%f\n',x1,x2);
end
end
4.给定半径,求球的体积和表面积。
r=input('input the Radius of ball:');
volume=(4/3)*pi*(r^3); %体积
surfArea=4*pi*(r^2); %表面积
fprintf('The surface area of the ball is %f.\nThe volume of the ball is %f.\n',surfArea,volume);
5.输入三个数,将其按照从小到大的顺序排列。
A=input('input three numbers:\nUsage:[ 1 2 3 ]');
for i=1:3
if A(2)<A(1)
tmp=A(2);
A(2)=A(1);
A(1)=tmp;
end
if A(2)>A(3)
tmp=A(3);
A(3)=A(2);
A(2)=tmp;
end
end
disp(A)