反转包含随机数的数组。如何?
Reverse an array containing random numbers. How?
我的任务是创建一个包含随机数的数组,然后在 C# 中反转顺序。
我设法生成了随机数组,但是我该如何反转它?
例如,输出应如下所示
15334
43351
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)
{
Random random = new Random();
int num = random.Next(TalArray.Length);
Console.WriteLine(num);
}
提前致谢! :)
你试过了吗
Documentation
public static void Main()
{
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)
{
Random random = new Random();
int num = random.Next(TalArray.Length);
arr[i] = num;
Console.WriteLine(num);
}
Array.Reverse(arr);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
工作示例dotnet fiddle
这是 Array.Reverse 的解决方案:
var arr = new int[5];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = new Random().Next(0, arr.Length);
}
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) + string.Join("", revArr));
我的任务是创建一个包含随机数的数组,然后在 C# 中反转顺序。
我设法生成了随机数组,但是我该如何反转它?
例如,输出应如下所示
15334 43351
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)
{
Random random = new Random();
int num = random.Next(TalArray.Length);
Console.WriteLine(num);
}
提前致谢! :)
你试过了吗 Documentation
public static void Main()
{
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)
{
Random random = new Random();
int num = random.Next(TalArray.Length);
arr[i] = num;
Console.WriteLine(num);
}
Array.Reverse(arr);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
工作示例dotnet fiddle
这是 Array.Reverse 的解决方案:
var arr = new int[5];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = new Random().Next(0, arr.Length);
}
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) + string.Join("", revArr));