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

49 ビュー (過去 30 日間)
zyxla
zyxla 2015 年 10 月 11 日
編集済み: Tamir Suliman 2018 年 1 月 7 日
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 Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by