Combining 2 codes to make a number counter with user input

1 回表示 (過去 30 日間)
Hayden Baks
Hayden Baks 2020 年 8 月 24 日
編集済み: Jan 2020 年 8 月 25 日
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 件のコメント
Walter Roberson
Walter Roberson 2020 年 8 月 24 日
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 2020 年 8 月 24 日
Why not use the sort() function???

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2020 年 8 月 25 日
編集済み: Jan 2020 年 8 月 25 日
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

カテゴリ

Help Center および File ExchangeWaveform Generation についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by