Entering numbers from the keyboard
30 次查看(过去 30 天)
显示 更早的评论
I want to input 4 numbers from the keyboard, then have the m file give me the largest and second largest numbers.
How do I check that the input is a number (and not a letter/other character) and how do I get the second largest number to be shown?
Also the programme should run continuously, taking 4 numbers at a time until the user wants to terminate, eg with an 'N' , how do I do this?
Thanks in advance
2 个评论
回答(2 个)
Image Analyst
2013-6-15
编辑:Image Analyst
2013-6-15
Start with this:
% Ask user for 4 numbers.
defaultValues = {'1', '2', '3', '4'};
titleBar = 'Enter values';
userPrompts = {'Enter number #1', 'Enter number #2', 'Enter number #3', 'Enter number #4'};
% Loop until user clicks Cancel
while true
caUserInput = inputdlg(userPrompts, titleBar, 1, defaultValues);
if isempty(caUserInput),break,end; % Bail out if they clicked Cancel.
[value1, value2, value3, value4] = caUserInput{:}
value1 = str2double(value1)
value2 = str2double(value2)
value3 = str2double(value3)
value4 = str2double(value4)
% Check for a valid number.
if isnan(value1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
message = sprintf('value1 is not a number.\nI said it had to be an number.');
uiwait(warndlg(message));
end
if isnan(value2)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
message = sprintf('value2 is not a number.\nI said it had to be an number.');
uiwait(warndlg(message));
end
if isnan(value3)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
message = sprintf('value3 is not a number.\nI said it had to be an number.');
uiwait(warndlg(message));
end
if isnan(value4)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
message = sprintf('value4 is not a number.\nI said it had to be an number.');
uiwait(warndlg(message));
end
end
0 个评论
Azzi Abdelmalek
2013-6-15
编辑:Azzi Abdelmalek
2013-6-15
for k=1:4
xvalue='';
while ~isnumeric(xvalue)
test=0;
text=sprintf('enter a value n°%d for x',k);
str=input(text,'s');
id=regexp(str,'\d*\.?\d*','match')
if isempty(id)
id={' '};
test=1;
end
if numel(id{:})==numel(str) & test==0 & ~isequal(str,'.')
xvalue=str2num(str)
else
xvalue=''
end
end
A(k)=xvalue
end
c=max(A)
8 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!