Why doesn't my code recognize the input function in the loop?

2 visualizaciones (últimos 30 días)
Dear community,
I am having issues with my following code:
% User is asked to enter numbers. Once they enter a 0, the amount of numbers entered prior is being displayed.
for i = n
numbers = input("Please enter a number: ")
if numbers~=0
input("Please enter a number: ")
else
fprintf("You entered %d numbers. ", length(numbers))
end
end
The print statement works, as long as I just have entered 0. But if there are more than two entries, nothing happens? Did I put in the input function at an inappropiate place? I am not sure what causes this to not put the input function "as a loop", as long as the entered number is not 0.
Kind regards,
Xena

Respuesta aceptada

Image Analyst
Image Analyst el 13 de Nov. de 2021
Try it this way:
% User is asked to enter numbers. Once they enter a 0, the amount of numbers entered prior is being displayed.
n = 9; % Whatever the maximum times you want to ask is.
count = 0;
for k = 1 : n
usersResponseS = input('Please enter a number: ', 's');
usersResponse = str2double(usersResponseS);
if isnan(usersResponse)
fprintf('%s is not a valid response. Enter a number, not a letter.\n', usersResponseS)
elseif usersResponse ~=0
% Increment count of valid numbers.
count = count + 1;
% Log this valid number to an array.
numbers(count) = usersResponse;
% fprintf("You have entered %d valid numbers.\n", count);
else
fprintf("You have entered %d valid numbers.\n", count);
break;
end
end

Más respuestas (1)

Awais Saeed
Awais Saeed el 13 de Nov. de 2021
Editada: Awais Saeed el 13 de Nov. de 2021
try this
ctr = 0;
for i = 1:1:3
numbers = input('Enter a number: ');
if numbers ~= 0
ctr = ctr + 1;
else
fprintf('You have entered %d valid numbers\n', ctr)
break;
end
end
  2 comentarios
Image Analyst
Image Analyst el 13 de Nov. de 2021
Huh?
for i = 1:1:3
numbers = input('Enter a number: ');
if numbers ~= 0
disp('invalid entry')
else
fprintf('You have entered %d\n', numbers)
end
end
is working for you? You might want to verify that.
Awais Saeed
Awais Saeed el 13 de Nov. de 2021
Seems I misunderstood the requirement. I thought the OP is asking for to say "invalid" for non-zero input and "valid" for 0 input. Anyways, I have updated the code.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by