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 Center および File ExchangeLoops 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