How can I apply the loop method for this program ?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
shyam
le 17 Fév 2014
Réponse apportée : Image Analyst
le 17 Fév 2014
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,
0 commentaires
Réponse acceptée
Image Analyst
le 17 Fév 2014
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Crystals dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!