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

回答(1 个)

Image Analyst
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 个评论
Thorsten
Thorsten 2015-11-9
编辑:Thorsten 2015-11-9
First line should read
num = 1;
and while condition should read
while num ~= 0
And you could rewrite the code without a break, if you like, since the while loop breaks if its condition is false.
Image Analyst
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by