another way to break without using the command 'break'
显示 更早的评论
Hi all,
In this code i want to know another way to break the code withoug using the 'break command': This break should happen when the remaining liquid in a silo is less than the volume of a container
function [FullContainers,RemainingLiquid] = myFunction(VolumeOfSilo)
% myFunction generates the number of containers that are filled by the
% liquid in a silo of a given volume and the Liters remaining in the silo
% after all the containers have been filled
% >> syntax >> [NoContainer,RemainingLiquid] = myFunction(volumeOfSilo)
c = 0 ; % initially we dont have any containers
vol = zeros() ; % preallocate for speed
while c >= 0
c = c + 1; % keep bringing containers
vol(c) = 280 + 150*rand ; % determine the volume of the container
if VolumeOfSilo >= vol(c)
RemainingLiquid = VolumeOfSilo - vol(c) ; % remaining liters after pouring
VolumeOfSilo = RemainingLiquid; % update the liters remaining in silo
FullContainers = c ;
elseif VolumeOfSilo < vol(c) %
FullContainers = 0 ;
RemainingLiquid = VolumeOfSilo ;
end
if VolumeOfSilo < vol(c)
break
end
end
end
采纳的回答
更多回答(1 个)
Bhaskar R
2020-1-25
You can set a flag variable to terminate while loop without using break keyword
term_while = true; % flag variable
c = 0 ; % initially we dont have any containers
vol = zeros() ; % preallocate for speed
while c >= 0 || term_while
c = c + 1; % keep bringing containers
vol(c) = 280 + 150*rand ; % determine the volume of the container
if VolumeOfSilo >= vol(c)
RemainingLiquid = VolumeOfSilo - vol(c) ; % remaining liters after pouring
VolumeOfSilo = RemainingLiquid; % update the liters remaining in silo
FullContainers = c ;
end
if VolumeOfSilo < vol(c) % help me to avoid using break
% break
term_while = false; % set flag variable to false so the loop stops
end
end
end
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!