随机输出数组中的值(一位园友问的)

1,随机输出数组中所有的值(不重复)

static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 4, 5 };
          int[]str=new int[array.Length];
          Random r = new Random();
          for (int i = 0; i < array.Length; i++)
          {
              int index = r.Next(array.Length);
              //判断是否已经包含
              if (str.Contains(array[index]))
              {
                  i--;
                  continue;
              }
              str[i] = array[index];
              //数组中直接输出,就可以不用下面的for循环
              //Console.WriteLine(str[i]);
          }
          for (int j = 0; j < str.Length; j++)
          {
              Console.WriteLine(str[j]);
          }
          Console.ReadKey();
View Code

效果如下

2,随机输出数组中的指定个数(不重复)

只需要把上面的稍微改变

static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 4, 5 };
          int[]str=new int[3];
          Random r = new Random();
          for (int i = 0; i < 3; i++)
          {
              int index = r.Next(array.Length);
              //判断是否已经包含
              if (str.Contains(array[index]))
              {
                  i--;
                  continue;
              }
              str[i] = array[index];
              //数组中直接输出,就可以不用下面的for循环
              //Console.WriteLine(str[i]);
          }
          for (int j = 0; j < str.Length; j++)
          {
              Console.WriteLine(str[j]);
          }
          Console.ReadKey();
View Code

效果如下

3,随机输出数组中的一个值(javascript版本)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="../../Scripts/jquery-2.1.1.min.js"></script>
    <script>
        var array = [1, 2, 3, 4, 5];
        var index = Math.floor((Math.random() * array.length));
        alert(array[index]);
    </script>
</head>
<body>
</body>
</html>
View Code

效果如下

转载于:https://www.cnblogs.com/valiant1882331/p/4073228.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值