Finding the geometric mean of inputted numbers??
조회 수: 10 (최근 30일)
이전 댓글 표시
Hello, I have some trouble with my code. The objective of it is to accept an arbitrary number of positive input values and calculate both the arithmetic mean, and the geometric mean of the numbers. For this I have to use a while loop to get my inputs for the number, and to terminate the inputs if the user enters a negative number. Here is what I have so far.
clc
clear
k = 0;
while k >= 0
a = input('Give me the first number');
b = input('Give me the second number');
c = input('Give me the third number');
x = geomean(a,b,c);
y = mean(a,b,c);
if a, b, c, d < 0;
break;
end
end
disp(x)
disp(y)
I keep getting an error that says "too many input arguments" for the geomean function. Can anyone help out?
댓글 수: 0
답변 (2개)
James Tursa
2017년 10월 20일
편집: James Tursa
2017년 10월 20일
Use the square brackets [ ] to concatenate your inputs into a vector. E.g.,
x = geomean([a,b,c]);
y = mean([a,b,c]);
Also, you probably meant something like this for your if-test
if any([a,b,c] < 0)
댓글 수: 0
Star Strider
2017년 10월 20일
One approach:
. . .
v = [a b c];
x = geomean(v);
y = mean(v);
. . .
댓글 수: 2
Star Strider
2017년 10월 20일
Looking at the code you posted, it seems ‘k’ never changes, so the while condition remains true. Also, the break should break out of the loop, but for some reason doesn’t. I replaced it with a return that does.
This works, and does not create an infinite loop. Experiment with it to get the result you want. (I replaced input with inputdlg because I prefer it. Change it back if that works best for you. It will not affect the rest of your code.)
The (Revised) Code —
k = 0;
while k <= 0
a = inputdlg('Give me the first number');
b = inputdlg('Give me the second number');
c = inputdlg('Give me the third number');
v = str2double([a b c]);
if any(v < 0)
return;
end
x = geomean(v);
y = mean(v);
k = k + 1;
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!