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.
  2 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 3 月 28 日
What do you mean pre-allocate the vector?
Like that?
count = input("How many numbers will you enter?: ");
numberVector = zeros(1, count);

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by