黑马程序员------入学资格-----数组和随机和Contains

来源:互联网 发布:有哪些软件源 编辑:程序博客网 时间:2024/05/09 18:34

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------


这里我们 产生一个int数组,长度为100,并向其中随机插入1-500,并且不能重复。代码如下


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace 面对对象版的对话机器人
{
    class Program
    {
        static void Main(string[] args)
        {
           int[] a = new int[100];// 这里我们定义一个长度为100的数组
           Random r = new Random();//这里我们定义一个叫r 的一个随机函数

           
           int b = 0;
           while (b < 100)
           {
               int rNumber = r.Next(1, 500);//这里是定义rNumber 的随机范围是1到500
               if (!a.Contains(rNumber))//这里是检查a这个数组中是否有重复的数字,如果没有就继续

               {
                   a[b] = rNumber;
                   b++;
               }
           }
           for (int i = 0; i < a.Length - 1; i++)// 这里是一个冒泡的排序
           {
               for (int j = 0; j < a.Length - 1 - i; j++)
               {
                   int temp;
                   if (a[j] < a[j + 1])
                   {
                       temp = a[j];
                       a[j] = a[j + 1];
                       a[j + 1] = temp;
                   }
               }
           }
               for (int i = 0; i < a.Length; i++)
               {
                   Console.WriteLine(a[i]);
               }
           Console.WriteLine();
           Console.WriteLine(a.Length);




               Console.ReadKey();


        } 
    }
}

---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

详细请查看:www.itheima.com


0 0