How can I apply the loop method for this program ?

조회 수: 1 (최근 30일)
shyam
shyam 2014년 2월 17일
답변: Image Analyst 2014년 2월 17일
I want create a program that continuously asks the user to enter numbers until the user enters a negative number. The numbers before the last one (non-negative numbers) are saved in a vector B. Then I want to display B and the average value in B. For instance, if the user enters 3, 5, 0, 7, 11, -3, the input stops and B is [3, 5, 0, 7, 11]. The average value of B is 5.2.
I know how to do it with the built-in functions of Matlab, but can not figure out how to do it with the loop method. Help !
Thanks,

채택된 답변

Image Analyst
Image Analyst 2014년 2월 17일
Try this:
count = 0;
defaultValue = 45;
titleBar = 'Enter a number';
userPrompt = 'Enter the number';
while count < 100 % failsafe - max amount we ever expect so don't get infinite loop
% Ask user for a number.
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),break,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
theNumber = str2double(cell2mat(caUserInput));
% Check for a valid integer.
if isnan(theNumber)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
theNumber = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', theNumber);
uiwait(warndlg(message));
end
% Exit if number is negative:
if theNumber < 0
break;
end
count = count + 1;
B(count) = theNumber;
end
if count >= 1
% Display B
B
% Display mean of B
meanB = mean(B);
fprintf('The mean of B = %.3f\n', meanB);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Crystals에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by