码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-11-04 12:41:38      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   os   java   for   sp   

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

bubuko.com,布布扣
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

效果如下

bubuko.com,布布扣

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

只需要把上面的稍微改变

bubuko.com,布布扣
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

效果如下

bubuko.com,布布扣

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

bubuko.com,布布扣
<!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

效果如下

bubuko.com,布布扣

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

标签:style   blog   http   color   ar   os   java   for   sp   

原文地址:http://www.cnblogs.com/valiant1882331/p/4073228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!