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

조회 수: 2 (최근 30일)
Xena Erzi
Xena Erzi 2021년 11월 13일
댓글: Xena Erzi 2021년 11월 14일
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

채택된 답변

Image Analyst
Image Analyst 2021년 11월 13일
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

추가 답변 (1개)

Awais Saeed
Awais Saeed 2021년 11월 13일
편집: Awais Saeed 2021년 11월 13일
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
Image Analyst
Image Analyst 2021년 11월 13일
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 2021년 11월 13일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by