c#Random类生成随机数

生成20个不同的随机数,要求利用一维数组来求解问题。利用Random类可生成随机数,每个数在10(含)和100(不含)之间。对这20个各不相同的数排序(使用Array.Sort()方法),最后输出。

using System;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[100];
            for (int i = 0; i < a.Length; i++)
                a[i] = i;
            Random r = new Random();
            //数组result用来保存随机生成的不重复的10个数
            int[] result = new int[20];
            int ulimit = 100;
            int id;
            for(int j = 0; j < 20; j++)
            {
                id = r.Next(10, ulimit - 1);
                result[j] = a[id];
                a[id] = a[ulimit - 1];
                ulimit--;
            }
            Array.Sort(result);
            foreach (int k in result)
            {
                Console.Write("{0} ", k);
            }
            Console.ReadKey();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值