c#实现随机产生不重复数字原理:随机产生数字 及检查重复
随机产生使用关键字:Random
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 随机生成
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random c = new Random();
int[] n = new int[5];
int[] index = new int[5];
private void button1_Click(object sender, EventArgs e)
{
string s = "";
//使用for循环实现产生5个随机数
for (int i = 0; i <= 4; i++)
{
n[i] = c.Next(0, 5);
//二层循环 实现不重复数字
for (int j = 0; j < i; j++)
{
if (n[i] == n[j])
{
i--;
}
}
}
//使用for循环遍历出来
for (int i = 0; i < n.Length; i++)
{
s = s + n[i].ToString() + ",";
}
//截取字符串
this.label1.Text = s.Substring(0, s.Length - 1);
}
}
}