zoukankan      html  css  js  c++  java
  • 随机输出数组中的值(一位园友问的)

    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

    效果如下

  • 相关阅读:
    2019 春第1次课程设计实验报告
    2019春第十二周作业
    2019春第十一周作业
    2019春第十周作业
    关于Vmvare虚拟机中Linux系统不能全屏的问题
    My algorithmic road
    段错误
    python人生如初见之初见yield
    网络爬虫requests-bs4-re-1
    The First Python man in Github
  • 原文地址:https://www.cnblogs.com/valiant1882331/p/4073228.html
Copyright © 2011-2022 走看看