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

조회 수: 19 (최근 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