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!