another way to break without using the command 'break'
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
Bhaskar R
le 25 Jan 2020
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
1 commentaire
suleiman abdullahi
le 25 Jan 2020
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!