Combining 2 codes to make a number counter with user input

조회 수: 2 (최근 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 CenterFile Exchange에서 Waveform Generation에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by