Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 25

1.1.9 Flow Control 1.1.9.1 if‐end and switch‐case‐end Statements

Оглавление

An ifend block basically consists of an if statement, a sequel part and an end statement categorizing the block. An if statement, having a condition usually based on the relational/logical operator (Table 1.4), is used to control the program flow, i.e. to adjust the order in which statements are executed according to whether or not the condition is met, mostly depending on unpredictable situations. The sequel part consisting of one or more statements may contain else or elseif statements, possibly in a nested structure containing another if statement inside it. The switch‐case‐end block might replace a multiple if‐elseif‐..‐end statement in a neat manner.

Table 1.4 Relational operators and logical operators.

Relational operator Remark
< Less than
<= Less than or equal to
== Equal
> Greater than
>= Greater than or equal to
∼= Not equal (≠)
& and
| or
not

Let us see the following examples:

1 (Ex. 1) A Simple if‐else‐end Block%nm119_1.m: example of if-end block t=0; if t>0 sgnt= 1; else sgnt= -1; end

2 (Ex. 2) A Simple if‐elseif‐end Block%nm119_2.m: example of if-elseif-end block if t>0 sgnt= 1 elseif t<0 sgnt= -1 end

3 (Ex. 3) An if‐elseif‐else‐end Block%nm119_3.m: example of if-elseif-else-end block if t>0, sgnt= 1 elseif t<0, sgnt= -1 else sgnt= 0 end

4 (Ex. 4) An if‐elseif‐elseif‐..‐else‐end Block%nm119_4.m: example of if-elseif-elseif-else-end block point= 85; if point>=90, grade= 'A' elseif point>=80, grade= 'B' elseif point>=70, grade= 'C' elseif point>=60, grade= 'D' else grade= 'F' end

5 (Ex. 5) A switch‐case‐end Block%nm119_5.m: example of switch-case-end block point= 85; switch floor(point/10) %floor(x): integer less than or equal to x case 9, grade= 'A' case 8, grade= 'B' case 7, grade= 'C' case 6, grade= 'D' otherwise grade= 'F' end

Applied Numerical Methods Using MATLAB

Подняться наверх