1

So basically Im writing a code where the user inputs the size of the array and the array generates random numbers, and then the user will enter 2 indexes where it will swap the indexes.

So far i only got the main part. Please help me. I got everything right except when i try to print on the swapped index array, it gives me an error.

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] + "");
    }   


}
4

1 回答 1

1

所以说你需要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 + "")

如果你想打印每个数字,你可以像这样打印它们:

for (int i=0; i < convertedSizeArray; i++) 
{
    Console.WriteLine(array[i] + "");
}
于 2013-04-29T13:45:39.977 回答