Filter löschen
Filter löschen

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

6 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Image Analyst
Image Analyst am 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

Weitere Antworten (1)

Awais Saeed
Awais Saeed am 13 Nov. 2021
Bearbeitet: Awais Saeed am 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 Kommentare
Image Analyst
Image Analyst am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by