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!