Having trouble with while loops problem

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 个评论

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.

请先登录,再进行评论。

 采纳的回答

Here are some things that are wrong:
  1. You're entering separate numbers x,y for the arithmetic and geometric means (you should be using x for both).
  2. Initially ttotal is zero, so every time you multiply it by something you get zero (try 1).
  3. If x<0, break, end is redundant (it's going to exit anyway at the top of the loop).
  4. You should save division by cnt to the end (otherwise you're dividing by 1, 2, 3, etc.). Ditto for the power of cnt/2.

2 个评论

Thanks! that fixed it, how do i get is to accept say 4 inputs and then calculate the average and geometric mean.
revised version:
ttotal=1;
total=0;
cnt=0;
while x>=0
x=input('Please enter a positive number:');
cnt=cnt+1;
total=total+x;
ttotal=(ttotal*y);
fprintf('The geometric mean is %g',ttotal^(cnt/2))
fprintf('The average of the inputed numbers is %g',total/cnt)
end
fprintf('Program-Terminated')
You're getting closer, but you haven't done point 4 yet (by end I mean *after* the loop). Also, think about when you should ask for a number. What happens when you enter a negative number? Finally, you might want to check your definition of a geometric mean.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心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!

Translated by