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

2 vues (au cours des 30 derniers jours)
Xena Erzi
Xena Erzi le 13 Nov 2021
Commenté : Xena Erzi le 14 Nov 2021
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

Réponse acceptée

Image Analyst
Image Analyst le 13 Nov 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

Plus de réponses (1)

Awais Saeed
Awais Saeed le 13 Nov 2021
Modifié(e) : Awais Saeed le 13 Nov 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 commentaires
Image Analyst
Image Analyst le 13 Nov 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 le 13 Nov 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by