gpt4 book ai didi

c# - 将数组中的元素右移 n

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:56 25 4
gpt4 key购买 nike

我想通过仅更改索引 将一个数组中的元素右移。另外我不想使用内置函数

例如,如果我们有

8,6,5,3,9

那么我们将有

9,8,6,5,3

如果数组没有足够的长度。其余元素将从数组的第一个索引开始移动。

   int index = 0, temp = 0;
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}

for (int i = 0; i < myarray.Length; i++)
{
if (myarray.Length <= i + 5)
{
index = ((i + 5) % 5);
temp = myarray[index];
myarray[index] = myarray[i];
myarray[i] = temp;
}
else
{
temp = myarray[i + 5];
myarray[i + 5] = myarray[i];
myarray[i] = temp;
}
}

这是我试过的方法,但是没有用

最佳答案

如果类次计数小于或等于数组大小,您可以使用此代码(我通过 this link 编辑了答案):

        using System;

int M = 5;//shift count
int size; //size of array
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}

size = myarray.Length;
if (size >= M)
{
Array.Reverse(myarray, 0, size);
Array.Reverse(myarray, 0, M);
Array.Reverse(myarray, M, size - M);

for (int i = 0; i < myarray.Length; i++)
{
Console.Write(myarray[i]+"\t");
}

Console.Read();
}

关于c# - 将数组中的元素右移 n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58745180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com