reads in n numbers from the user storing the numbers in a vector. Print the numbers from the ends inwards (last, first, second last, second, third)

조회 수: 1 (최근 30일)
How many numbers will you enter?: 5
Enter a number: 3
Enter a number: 5
Enter a number: 6
Enter a number: 4
Enter a number: 3
Your numbers from outside to middle are: 3 3 4 5 6
Let the element output follow the following rules: output last bit, output first, output penultimate second, input second
This is my code
%current is going from 1 to length of vector(maybe)
current = 0;
num = input('How many numbers will you enter?: ');
vector = [];
for i = 1:num
ele = input("Please enter the elements: ");
vector = [vector ele];
end
for current = 0:ceil(length(vector)/2)
%A = input('Enter a number');
fprintf("%d %d ",vector(length(vector)-current),vector(current+1));
%A(length(A)-current),A(current+1));
end
It will have extra numbers in the last. like that
How many numbers will you enter : 6
Please enter the elements: 1
Please enter the elements: 2
Please enter the elements: 3
Please enter the elements: 4
Please enter the elements: 5
Please enter the elements: 6
6 1 5 2 4 3 3 4
How to improve this code?
  댓글 수: 1
Rik
Rik 2022년 8월 19일
@Cheryl Pope:
For this question you have even less standing than the other question you requested deletion for.
You can contact Mathworks support if you want either to be deleted, I will not do so.

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2022년 3월 28일
You are asking the user for the number of elements. You should use that to pre-allocate the vector array so you can use indexing in your first loop.
For the second loop you should create a vector with the appropriate indices. Changing ceil to floor will not fix the problem. Perhaps the sort function can help you generate the indices.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by