Having trouble with while loops problem
Show older comments
I'm required to write a program what will accept positive numbers, and calculate both the average of them and the geometric mean(nth root of (x1*x2*x3...*xn). While loops are to be used to get the input numbers, and terminate the inputs that are negative. While loops in general confuse me so can you please tell me what i did wrong.
ttotal=0;
total=0;
cnt=0;
x=1;
y=1;
while x>=0
x=input('Please enter a positive number:');
cnt=cnt+1;
total=(total+x)/cnt;
if x<0
break;
end
while y>=0
y=input('Please enter a positive number:');
cnt=cnt+1;
ttotal=(ttotal*y)^(cnt/2);
if y<0
break;
end
fprintf('The geometric mean is %g',ttotal)
fprintf('The average of the inputed numbers is %g',total)
end
end
fprint('Program-Terminated')
1 Comment
Paulo Silva
on 8 Mar 2011
instead of while x>=0 and y>=0 use while 1
put if x<0,break,end after the user input x and
if y<0,break,end after the user input y
Follow Andrew tips and you should be fine.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!