How do I complete this script for below question? I have partially created the script: see it below the question.
1 次查看(过去 30 天)
显示 更早的评论
Write a script that asks for a series of numbers and calculates the sum and the mean. When the user enters a value of 0, the script stops and performs the calculation. For example:
Enter a number (type 0 to end) : 5
Enter a number (type 0 to end) : 6
Enter a number (type 0 to end) : 7
Enter a number (type 0 to end) : 8
Enter a number (type 0 to end) : 0
4 numbers entered. Sum=26. Mean=6.5.
% initialisation
num==0;
while num==0
num=input('Enter a number (type 0 to end): ');
end %end while loop
2 个评论
Image Analyst
2015-11-9
I'll fix the formatting for you this time, but please read this for next time: http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
回答(1 个)
Image Analyst
2015-11-9
Have an accumulator variable (not named sum, which is a built in function name):
% initialisation
num==0;
theSum = 0;
loopCounter = 0;
while num==0
num=input('Enter a number (type 0 to end): ');
if num == 0
break;
end
theSum = theSum + num;
loopCounter = loopCounter + 1;
end %end while loop
if loopCounter >= 1
fprintf('%d numbers entered. Sum=%f. Mean=%.1f\n',...
loopCounter, theSum, theSum/loopCounter);
else
fprintf('0 numbers entered.\n');
end
2 个评论
Image Analyst
2015-11-9
Correct (I didn't notice the errors he had in his existing code).
Without the break line, you'd have to subtract 1 from the loop counter after the loop exits.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!