MATLAB Answers

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

조회 수: 126(최근 30일)
zyxla
zyxla 11 Oct 2015
편집: Tamir Suliman 7 Jan 2018
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.

  댓글 수: 0

로그인 to comment.

답변(2개)

Image Analyst
Image Analyst 11 Oct 2015
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

  댓글 수: 0

로그인 to comment.


Tamir Suliman
Tamir Suliman 7 Jan 2018
편집: Tamir Suliman 7 Jan 2018
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:

  댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by