another way to break without using the command 'break'
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (1)
Bhaskar R
il 25 Gen 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 Commento
suleiman abdullahi
il 25 Gen 2020
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!