我需要做什么以获得一个随机生成的数组与用户输入,然后输入两个索引交换它们?
问题描述:
所以基本上我编写一个代码,其中用户输入数组的大小和数组生成随机数,然后用户将输入2个索引将交换索引。我需要做什么以获得一个随机生成的数组与用户输入,然后输入两个索引交换它们?
到目前为止,我只得到了主要部分。请帮帮我。除了当我尝试在交换索引数组上打印时,我得到了一切,它给了我一个错误。
using System;
class MainClass
{
public static void Main (string[] args)
{
int[] randomSizedArray;
string sizeOfArray;
int convertedSizeArray = -1;
Console.WriteLine ("Please Enter the Size of the Array Between 1-99");
sizeOfArray = Console.ReadLine();
convertedSizeArray = Int32.Parse(sizeOfArray);
;
randomSizedArray= new int[convertedSizeArray];
Random rnd = new Random();
for (int i=0; i < convertedSizeArray; i++) {
randomSizedArray[i] = rnd.Next(1,99);
}
for (int i=0; i < convertedSizeArray; i++)
{
Console.WriteLine(randomSizedArray[i] + "");
}
string swapindex1;
string swapindex2;
int index1;
int index2;
Console.WriteLine("Please Enter Index to swap");
swapindex1 = Console.ReadLine();
index1 = Int32.Parse(swapindex1);
int temp = randomSizedArray[index1];
Console.WriteLine ("Please Enter a Second Value to swap");
swapindex2 = Console.ReadLine();
index2 = Int32.Parse(swapindex2);
randomSizedArray[index1] = randomSizedArray[index2];
randomSizedArray[index2] = temp;
Console.WriteLine(randomSizedArray[temp] + "");
}
}
答
所以说,你需要随机数介于0和10
array = new int[convertedSizeArray];
for (int i=0; i < convertedSizeArray; i++)
{
array[i] = rnd.Next(11);
}
然后,你可以问两个数字你问数组长度相同的方式切换他们
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
如果你想打印一个int你必须做Console.WriteLine(randomSizedArray.ToString())
或Console.WriteLine(randomSizedArray + "")
A第二,如果你要打印的每个号码你可以打印出来是这样的:
for (int i=0; i < convertedSizeArray; i++)
{
Console.WriteLine(array[i] + "");
}
这就是我说,是啊...... – 2013-04-29 13:50:00
所以阵列=新的INT [convertedSizeArray] (int i = 0; i
Larryjohncarter
2013-04-29 13:50:11
第二部分切换给定索引处的数字。您可以按照您询问数组长度的相同方式从用户那里获取两个索引。我假设你将这些值存储在'int index1'和2 – 2013-04-29 13:51:58