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?

回答(2 个)

James Tursa
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)

Star Strider
Star Strider 2017-10-20
One approach:
. . .
v = [a b c];
x = geomean(v);
y = mean(v);
. . .
  2 个评论
Matt Amador
Matt Amador 2017-10-20
I seemed to have changed something but now I am in an infinite loop where it asks me for the three inputs over and over. What went wrong?
clc
clear
k = 0;
while k <= 0
a = input('Give ne the first number');
b = input('Give me the second number');
c = input('Give me the third number');
v = [a b c];
x = geomean(v);
y = mean(v);
if any([a,b,c]< 0)
break;
end
end
disp(x)
disp(y)
Star Strider
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 CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by