怎样 随机选出 ..不重复的数字喃 ?

w312211938 2009-04-25 11:32:57
string s = String.Empty;
int len = li.Count;
Random rand = new Random(len);
for (int i = 0; i <6; i++)
{
int r = rand.Next(0,len );
temp = li[r];
s += Convert.ToString(temp) + " ";
textBox1.Text = s;

}

这样会有重复的 数字 ... 怎么让它产生不重复的数字喃?
...全文
68 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
acol 2009-04-27
  • 打赏
  • 举报
回复
用indexOf(产生的数字)==-1就继续
zhu4139365 2009-04-27
  • 打赏
  • 举报
回复
宣告一個陣列,利用隨機數產生器Random.Next(),來設計一個程式由電腦產生出1~13的數字共13個,且數字不得重複。
EX:1、6、2、9、11、5、8、10、3、12、7、4、13。

using System;
using System.Collections.Generic;
using System.Text;
namespace Rnd13
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
//1~13取亂數 不重複
int n = 13;
int[] b = new int[13]; //設13個陣列//
while (n != 0)
{
int t = rnd.Next(13); //取亂數//
if (b[t] != -1) //b[t]不等於-1//
{
Console.Write("{0} ", t + 1); //把質列出//
b[t] = -1; //b[t]等於-1就不取//
--n;
}
}
}
}
}
xunaipeng 2009-04-27
  • 打赏
  • 举报
回复
做个判断,过滤一下啊!
freewind0521 2009-04-27
  • 打赏
  • 举报
回复
每次判断一下,如果已经存在,就不添加进去
yangqidong 2009-04-25
  • 打赏
  • 举报
回复
string s = String.Empty;
int len = li.Count;
Random rand = new Random(len);
for (int i = 0; i <6; i++)
{
int r = rand.Next(0,len );
temp = li[r];
if(!s.Contains(temp.ToString()))
{
s += Convert.ToString(temp) + " ";
textBox1.Text = s;
}
else i--;
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧