MATLAB嵌套if-else语句

本文概述

  • 句法
  • 例1
  • 例子2
  • if语句可以嵌套, 但是每个if语句都需要end关键字。
句法
if expression Statements if expressionStatements elseStatements endelseif expression Statements if expressionStatements endelse Statementsend

例1
% nested if-elseif-else programnum = randi(100, 1); a = input('enter a number greater than 1 and less than 10 : ')disp(['the random number is : ', num2str(num)])if a < = 1 || a > = 10disp('please try again & enter the number in between 1 & 10')elseif rem(num, a) == 0if rem(num, 2) == 0if rem(a, 2) == 0disp('you entered an even number, and the random number is also even')elsedisp('random number is even and divisible by the entered number')endelsedisp('random number is odd but divisible by the entered number')endelseif num < adisp('random number is smaller than theentered number, please try again ')elsedisp('random number is not divisible by the entered number')end

【MATLAB嵌套if-else语句】输出
enter a number greater than 1 and less than 10: 9a = 9the random number is: 14the random number is not divisible by the entered number

例子2
% create a random number, max. 100, and a scalara = randi(100, 1)% use quorem function(takes symbolic variables as arguments) to get quotient & remainder[Q, R] = quorem(sym(a), sym(2))if R == 0if rem(Q, 2) == 0disp('random number-even')disp('result-even')elsedisp('random number-even')disp('result-odd')endelseif rem(Q, 2) == 0disp('random number-odd')disp('result-even')elsedisp('random number-odd')disp('result-odd')endend

    推荐阅读