Combining 2 codes to make a number counter with user input

1 vue (au cours des 30 derniers jours)
Hayden Baks
Hayden Baks le 24 Août 2020
Modifié(e) : Jan le 25 Août 2020
I have two pieces of code and i am trying to amalgamate the two. Basically i need a number sorter which asks the user to input values until a number equal to or less than 0 is input. Once this is done the program sorts the numbers into ascending order. So far I have code for user input that ends when a number less than 0 is entered
function Sample()
Loop = true;
Count = 0;
while(Loop)
a = input('Please input a number: ');
if a>=0
Count = Count+1;
else
Loop = false;
end
end
fprintf('Ok, the number of inputs enetered by the user is %d',Count);
end
And a code to put numbers into ascending order.
A = [1 2 4 8 5 11 0.2];
B = zeros(size(A));
for k = 1:numel(A)
[m, ind] = min(A);
A(ind) = [];
B(k) = m;
end
disp(B)
I cant however figure out how to combine the two into a single program. Any help would be greatly appreciated
  2 commentaires
Walter Roberson
Walter Roberson le 24 Août 2020
The first thing you need to do is change Sample so that it keeps track of all the the entered numbers except the termination. Then have it return the list of numbers. Calling Sample would replace the assignment to A in your second code.
Image Analyst
Image Analyst le 24 Août 2020
Why not use the sort() function???

Connectez-vous pour commenter.

Réponses (1)

Jan
Jan le 25 Août 2020
Modifié(e) : Jan le 25 Août 2020
function v = Sample()
Loop = true;
Count = 0;
v = [];
while Loop
a = input('Please input a number: ');
if a >= 0
Count = Count + 1;
v(Count) = a;
else
Loop = false;
end
end
fprintf('Ok, the number of inputs enetered by the user is %d\n', Count);
v = sort(v);
end

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by