How can I use a while loop to check input for negative numbers and non-numerical input?

17 次查看(过去 30 天)
Hi, I'm very new to matlab and my issue might be very simple, but I've been trying and failing to use a while loop to check an input. I tried to base it off of what I read in my textbook and a sample format, like this:
inputnum=input('Enter a positive number: ');
while inputnum>=0
fprintf('You entered a %d. \n\n', inputnum)
inputnum=input('Enter a positive number: ');
end
I have tried many variations and can't seem to get it to work. I just need to check that the input entered by the user is a number (not a character/string, and not negative), and have the script give them the option to enter the input again rather than just ending the program. How can I do this? Thanks.

回答(2 个)

Image Analyst
Image Analyst 2015-10-11
See this snippet:
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end

Tamir Suliman
Tamir Suliman 2018-1-7
编辑:Tamir Suliman 2018-1-7
inputnum=input('Enter a positive number: ');
while inputnum<0
fprintf('You entered a %d. \n\n', inputnum)
inputnum=input('Enter a positive number: ');
end
You only need to change the > sign to < the logic was just wrong
Enter a positive number: -1 You entered a -1.
Enter a positive number:

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by