个性化阅读
专注于IT技术分析

MATLAB嵌套if-else语句

本文概述

  • if语句可以嵌套, 但是每个if语句都需要end关键字。

句法

if expression
	Statements
	if expression
		Statements
	else
		Statements
	end
elseif expression
	Statements
	if expression
		Statements
	end
else 
	Statements
end

例1

% nested if-elseif-else program
num = 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 >= 10
    disp('please try again & enter the number in between 1 & 10')
elseif rem(num, a) == 0
        if rem(num, 2) == 0
            if rem(a, 2) == 0
                disp('you entered an even number, and the random number is also even')
            else
                disp('random number is even and divisible by the entered number')
            end
        else
            disp('random number is odd but divisible by the entered number')
        end
elseif num < a
    disp('random number is smaller than the  entered number, please try again ')
else
    disp('random number is not divisible by the entered number')
end

输出

enter a number greater than 1 and less than 10: 9
a = 9
the random number is: 14
the random number is not divisible by the entered number

例子2

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

赞(0)
未经允许不得转载:srcmini » MATLAB嵌套if-else语句

评论 抢沙发

评论前必须登录!