My while loop and rem function create an infinite loop
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Krista Clark
el 27 de Feb. de 2021
Comentada: Krista Clark
el 28 de Feb. de 2021
I have to use a while loop to ensure user input is an integer between 3 and 50. I set up constraints to do this but once I use the rem function to flag for noninteger it runs and infinite loop for my fprintf. What am I doing wrong?
%get user input
prompt = ('Enter a number for the length of your array: ');
x = input(prompt);
%have user input be an integer between 3-50
%test for noninteger
while (x < 3 || x > 50 || rem(x,1) ~= 0)
fprintf('Please enter an integer between 3 and 50: ');
end
0 comentarios
Respuesta aceptada
Walter Roberson
el 27 de Feb. de 2021
You do give a chance for the user to enter x again, so you are testing the same x each time.
3 comentarios
Walter Roberson
el 28 de Feb. de 2021
%get user input
prompt = ('Enter a number for the length of your array: ');
x = input(prompt);
%have user input be an integer between 3-50
%test for noninteger
while (x < 3 || x > 50 || rem(x,1) ~= 0)
fprintf('Please enter an integer between 3 and 50: ');
x = input(prompt);
end
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!