Finding the geometric mean of inputted numbers??
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
James Tursa
el 20 de Oct. de 2017
Editada: James Tursa
el 20 de Oct. de 2017
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 comentarios
Star Strider
el 20 de Oct. de 2017
One approach:
. . .
v = [a b c];
x = geomean(v);
y = mean(v);
. . .
2 comentarios
Star Strider
el 20 de Oct. de 2017
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
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!