MATLAB程序设计-分支结构

分支结构

a = 20;
b = -2;
c = 0;
d = 1;
%if结构
if a<12
    a = a + 4;
elseif (a>12)&(a<24)
    a = a + 8;
else 
    a = a + 12;
end
%检验判别式
if (b^2 - 4*a*c)>0
    disp('this equation has two complex roots');
elseif (b^2 - 4*a*c)==0
    disp('this equation has two identical real roots')
else
    disp('Write msg that equation has two distinct real roots')
end

分支结构的应用

  • 求解二次方程的根
%求解二次方程的根
disp('equation of the form A*X^2 + B*X + C = 0');
a = input('Enter the coefficient A:');
b = input('Enter the coefficient B:');
c = input('Enter the coefficient C:');
disc = b^2 - 4*a*c;
if disc>0
    x1 = (-b - sqrt(disc))/(2*a);
    x2 = (-b + sqrt(disc))/(2*a);
    fprintf('x1= %f\n',x1);
    fprintf('x2=%f\n',x2);
elseif disc==0
    x = -b/(2*a);
    fprintf('x=%f\n',x);
else
    real_part = -b/(2*a);
    imag_part = sqrt(abs(disc))/(2*a);
    fprintf('x1=%f +i%f\n',real_part,imag_part);
    fprintf('x1=%f -i%f\n',real_part,imag_part);
end

  • 求解二元函数的解
%求解二元函数的解
disp('Enter the values');
x = input('Enter coggicient x:');
y = input('Enter coggicient y:');
if (x>=0)&(y>=0)
    f = x+y;
elseif (x>=0)&(y<0)
    f = x+y^2;
elseif (x<0)&(y>=0)
    f = x^2+y;
else
    f = x^2+y^2;
end
fprintf('f=%f\n',f);
    

switch语句

%switch结构
value = input('the value:');
switch(value)
    case{1,3,5,7,9}
        disp('the value is odd');
    case{2,4,6,8,10}
        disp('the value is even');
    otherwise
        disp('the value is out of range');
end

try/catch结构

%try/catch结构
try
    fprintf(values);
catch
    disp('上面的代码错了');
end

发布了51 篇原创文章 · 获赞 29 · 访问量 2366

猜你喜欢

转载自blog.csdn.net/fangweijiex/article/details/103905726