📅  最后修改于: 2021-01-07 02:18:09             🧑  作者: Mango
break语句终止for循环或while循环的执行。当遇到break语句时,执行将继续循环外的下一条语句。在嵌套循环中,中断仅存在于最内部的循环中。
break
% program to break the flow at a specified point
a = randi(100,6,6)
k = 1;
while k
disp('program running smoothly')
if a(k) == 27
disp('program encounters the number 27, which is not useful for the current program;')
disp(['at index no.:',num2str(k)])
disp('so loop terminates now.....bye bye')
break
end
k = k+1;
end
输出:
a = 6×6
82 17 70 54 54 10
27 18 70 66 33 27
60 43 64 41 11 16
3 10 4 82 62 29
43 60 7 72 78 45
32 48 32 97 43 53
program running smoothly
program running smoothly
program encounters the number 27, which is not useful for the current program;
at index no.:2
so loop terminates now.....bye bye
范例2:
% program to terminate the execution on finding negative input
a = randn(4)
k = 1;
while k < numel(a)
if a(k) < 0
break
end
k = k + 1;
end
disp(['negative number :', num2str(a(k)), ',found at index: ', num2str(k),',hence the program terminated'])
输出:
a = 4×4
0.2398 -1.6118 0.8617 0.5812
-0.6904 -0.0245 0.0012 -2.1924
-0.6516 -1.9488 -0.0708 -2.3193
1.1921 1.0205 -2.4863 0.0799
negative number :-0.69036,found at index: 2,hence the program terminated
程序使用break语句终止执行流程。
例:
假设我们有一个在温度变化下运行的系统。环境温度决定了系统的运行。如果环境温度超过危险极限,则程序必须停止执行运行系统的应用程序。
工作温度范围根据某些预定条件而变化。因此,在夏季,当热浪可能损坏复杂的系统,或者在冬季温度下降到指定极限以下时,我们需要保护系统免于掉落。
温度范围从-100°C到+ 600°C。
该系统安装在世界各地。温度的某个地方以摄氏度为单位,温度的某个地方以华氏度为单位。因此,我们还需要注意这些温度单位。
need to take care of these temperature units also.
% Program to break the flow of Execution
u = symunit; % symunit returns symbolic unit
f = randi(200,4,4) % assume this function returns temperature in Fahrenheit
tf = {f,u.Fahrenheit}; % create cell array by adding Fahrenheit unit
tc = unitConvert(tf,u.Celsius,'Temperature','absolute'); % conversion to Celsius
vpan = vpa(tc,3) % conversion from equation to decimal form
min_t = -10; % minimum temperature
max_t = +60; % maximum temperature
tcd = double(separateUnits(vpan)); % convert to double by separating unit symbol
for k = 1:16
if (tcd(k) <= min_t)
disp(['application stopped, temperature dropped below the limit of -10 & current temp is : ',num2str(tcd(k)),'degree'])
break
else
if (tcd(k) >= max_t)
disp(['application stopped, temperature exceeds limit of +60 & current temp is : ',num2str(tcd(k)),'degree'])
break
end
end
end