How can I get a user to input a number which is not already

1 次查看(过去 30 天)
Hi, I just want a user to input(input must be between 1-9) a new number, so store the input value in a vector and add every new input to that vector and every time the user input new number I just use a code to check is the input is already in the vector, but my code is not check every value in the vector.
o=[];
for i=1:4
num=input('Enter:');
while num<=0||num>=9
num=input('Enter exist number:');
end
for i=1:length(o)
if num==o(i)
while num==o(i)
num=input('Enter new:');
end
end
end
o=[o num];
end
This is my code, can anyone please help
Thanks,

采纳的回答

Rik
Rik 2023-4-22
What you need to do, is to put your input statement at the start of the while loop, and then you can use ismember instead of a loop to check for matches.
Note that you should ask the user for the number in a char vector, and then use str2double to convert the char to a number.
The bottom line is that you should split the tasks of asking the user for a number and validating that input. You should write it in such a way that you can put those things in separate functions.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by