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 个评论
Paulo Silva
2011-3-8
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.
采纳的回答
更多回答(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!