While Loop wont calcuate my harmonic mean?

I dont see any reason why my program wont calculate the harmonic mean of the inputed numbers. The formula for the harmonic mean is ((N)/((1/x1)+(1/x2)...+(1/xn)))
Here's what i got:
total=0;
cnt=0;
x=1;
while x~=0
x=input('Please input a positive number(0 to quit):');
if x<0
break;
end
if x==0
break;
end
cnt=cnt+1;
total=(1/total) + (1/x);
end
hmean=cnt/total;
if x<0
fprintf('Error - Negative Inputs Entered, Program Terminated')
else
fprintf('\nThe harmonic mean is %g',hmean)
end

 채택된 답변

Matt Tearle
Matt Tearle 2011년 3월 10일

0 개 추천

total starts at 0, but then you have total=(1/total)+... That line should be total = total + (...) anyway.
BTW, I'm assuming you just can't use harmmean (from Statistics Toolbox)
As an aside, why not clean up the logic in the while loop by doing
if x>0
<calculate mean>
end
It will break out of the loop when x==0 anyway (so you don't really need the break).

댓글 수: 3

Walter Roberson
Walter Roberson 2011년 3월 10일
The while x=~0 is redundant and can be replaced with
while true
John
John 2011년 3월 10일
Thanks to both of you!
Matt Tearle
Matt Tearle 2011년 3월 10일
Just to clarify, Walter's suggestion works *if* you keep the "break"s you currently have. If you do what I said (get rid of the "break"s and use "if x>0..." instead, then don't change to "while true". That would be bad!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2011년 3월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by